package com.iris.live.services.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.iris.live.services.common.*;
import com.iris.live.services.common.reconsitution.MessageContext;
import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.RequestBase;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.report.ExcelReportContext;
import com.iris.live.services.report.IExcelReportService;
import com.iris.live.services.report.IExcelReportSource;
import com.iris.live.services.services.BrandService;
import com.iris.live.services.services.FinanceService;
import com.iris.live.services.vo.crm.QuoteFinanceInfo;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.security.acl.Group;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by sxy on 2016/7/27.
 */
@Service
@Transactional//(readOnly = true)
public class FinanceServiceImpl implements FinanceService {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(FinanceServiceImpl.class);
    @Autowired
    FinanceCancelReasonRepository financeCancelReasonRepository;
    @Autowired
    private FinanceRepository repository;
    @Autowired
    private Lsh金融设置Repository lsh金融设置Repository;
    @Autowired
    private Lsh经销商表Repository lsh经销商表Repository;
    @Autowired
    private Lsh金融战败原因Repository lsh金融战败原因Repository;
    @Autowired
    private Lsh金融机构设置Repository lsh金融机构设置Repository;
    @Autowired
    private Lsh金融机构手续费Repository lsh金融机构手续费Repository;
    @Autowired
    private Lsh金融季度额外奖励Repository lsh金融季度额外奖励Repository;
    @Autowired
    private 报价单表Repository 报价单表Repository;
    @Autowired
    private 报价金融表Repository 报价金融表Repository;
    @Autowired
    private Lsh先享后选设置Repository lsh先享后选设置Repository;
    @Autowired
    private Lsh金融申请表Repository lsh金融申请表Repository;
    @Autowired
    private DictionaryRepository t;
    @Autowired
    private LSH金融设置适用车型Repository lsh金融设置适用车型Repository;
    @Autowired
    private Lsh金融战败原因附属Repository lsh金融战败原因附属Repository;
    @Autowired
    private Lsh金融服务费Repository lsh金融服务费Repository;
    @Autowired
    private 报价金融详细表Repository 报价金融详细表repository;
    @Autowired
    private 报价客户表Repository 报价客户表repository;
    @Autowired
    private 金融礼物表Repository 金融礼物表repository;
    @Autowired
    private Lsh金融申请附属Repository lsh金融申请附属Repository;
    @Autowired
    private 顾客记录汇总Repository 顾客记录汇总repository;
    @Autowired
    private FinanceLogRepository financeLogRepository;
    @Autowired
    private Lsh消息Repository lsh消息Repository;
    @Autowired
    private 报价付款详细Repository 报价付款详细repository;
    @Resource
    private FinanceProductHotRankRepository fiProHoRaRep;

    @Autowired
    private 报价金融表LogModelRepository 报价金融表LogModelrepository;

    @Autowired
    private Lsh金融申请LogRepository lsh金融申请logxxdrepository;

    @Autowired
    private DetaillogModelRepository detaillogModelRepository;

    @Autowired
    private ApproveHistoryLogRepository approveHistoryLogRepository;

    @Autowired
    private 用户Repository 用户repository;

    @Autowired
    private Lsh车型Repository lsh车型Repository;

    @Autowired
    private TVehicleModelMapRepository tVehicleModelMapRepository;

    @Autowired
    private IExcelReportService reportService;

    @Resource(name = "ExportFinanceAccountInfoSource")
    private IExcelReportSource ExportFinanceAccountInfoSource;

    @Resource(name = "ExportFinanceLoanInfoSource")
    private IExcelReportSource ExportFinanceLoanInfoSource;

    @Autowired
    private  Itask基础设置Repository  itask基础设置Repository;

    @Autowired
    private 报价交车表Repository repository报价交车表;

    @Autowired
    private BrandService brandService;

    @Autowired
    private GroupAreaRepository groupAreaRepository;

    /**
     * 金融业务数据
     */
    @Override
    public PageData getFinanceInfoList(String permit, GetFinanceInfoListRequest request) {
        request = MoreObjects.firstNonNull(request, new GetFinanceInfoListRequest());
        return this.repository.getFinanceInfoList(request.getPageSize(), request.getPageIndex(), permit, request.permit,
                request.username, request.userPhone, request.financeCompany, request.financeStatus,
                request.financeProduct);
    }

    @Override
    public PageData getFinanceProductList(String permit, GetFinanceProductListRequest request) {
        request = MoreObjects.firstNonNull(request, new GetFinanceProductListRequest());
        GroupAreaModel groupAreaModel = groupAreaRepository.getInfoByPermit(permit);
        String parentPermit = null;
        if (1 == groupAreaModel.getIsDealer()) {  // 经销商登陆
            parentPermit = groupAreaRepository.getParentPermitByPermit(permit);
        }
        PageData page = this.repository.getFinanceProductList(request.getPageSize(), request.getPageIndex(), permit,
                request.productType, request.startDate, request.endDate, request.startAnnualRate,
                request.endAnnualRate,
                request.code, request.isValid, request.permissionCode, request.period, request.anJieType, request.IsStandard , request.brand,groupAreaModel.getIsDealer(),parentPermit);
        List<String> brands = brandService.getBrandListByPermit(permit);
        List list = page.getData();
        int total = page.getTotal();
        boolean permitFlag = ApprovalUtils.GROUP_PERMIT.equals(permit);
        Iterator iterator =  list.iterator();
        while(iterator.hasNext()){
            Map map = (Map) iterator.next();
            int id = (int) map.get("金融编号");
            List cars = this.repository.getProductSuitableCarListFilterModel(id,brands,permitFlag);
            if((cars==null||cars.size()==0)&&!permitFlag){
                iterator.remove();
                total--;
            }else{
                map.put("适用车型",cars);
            }
        }
        page.setTotal(total);
        return page;
    }

    @Override
    public ResultData getFinancePoundageList(String permit, GetFinancePoundageListRequest request) {
        request = MoreObjects.firstNonNull(request, new GetFinancePoundageListRequest());
        ResultData result = new ResultData("false",null,null);
        try {
            GroupAreaModel groupAreaModel = groupAreaRepository.getInfoByPermit(permit);
            String parentName = groupAreaRepository.getParentPermitByPermit(permit);
            List<String> brands = brandService.getBrandListByArea(groupAreaModel);
            PageData page = this.repository.getFinanceOrg(request.getPageSize(), request.getPageIndex(), permit,
                    request.permissionCode,parentName);
            List<Map> list = page.getData();
            if(!ApprovalUtils.GROUP_PERMIT.equals(permit)){ //如果为LSH许可,则全部展示
                if(groupAreaModel.getIsDealer()!=1) { // 为区域许可,则过滤适用区域
                    list = list.stream()
                            .filter(e -> brands.contains(e.get("品牌").toString()) && (e.get("区域许可")==null||e.get("经销店许可").toString().equals("") || e.get("区域许可").toString().equals(permit)))
                            .collect(Collectors.toList());
                }else{ // 为经销商许可,则过滤适用单店
                    list = list.stream()
                            .filter(e -> (permit.equalsIgnoreCase(e.get("许可").toString()))||     //(sql已经是经销商查询,经销商不需要过滤单店)
                                    (brands.contains(e.get("品牌").toString()) && (((e.get("经销店许可")==null||e.get("经销店许可").toString().equals(""))&&(e.get("区域许可")==null||e.get("区域许可").toString().equals("") || e.get("区域许可").toString().equals(parentName))) || (e.get("经销店许可").toString().equalsIgnoreCase(permit)&&e.get("区域许可").toString().equalsIgnoreCase(parentName)))))
                            .collect(Collectors.toList());
                }
                page.setTotal(list.size());
                page.setData(list);
            }

            result.setResult("true");
            result.setMessage(page.getTotal()+"");
            result.setPageData(page);
        }catch(Exception e){
        }
        /*for (Object data : page.getData()) {
            Map map = (Map) data;
            int financeCode = Integer.parseInt(map.get("金融机构编号").toString());
            List list = this.repository.getFinancePoundageList(financeCode);
            map.put("手续费收取", list);
//            int orgCode = Integer.parseInt(map.get("金融机构编号").toString());
//            List list_ex = this.repository.getFinancePoundageList_Ex(orgCode, null);
//            map.put("季度额外奖励", list_ex);
        }*/
        return result;
    }

    @Override
    public PageData getFirstUseProductList(String permit, GetFirstUseProductListRequest request) {
        request = MoreObjects.firstNonNull(request, new GetFirstUseProductListRequest());


        PageData page = this.repository.getFirstUseProductList(request.getPageSize(), request.getPageIndex(), permit,
                request.brand, request.carCode, request.carDetail, request.startDate, request.endDate,
                request.startAnnualRate, request.endAnnualRate, request.param, request.permissionCode);

        for (Object data : page.getData()) {
            Map map = (Map) data;
            int financeCode = Integer.parseInt(map.get("金融编号").toString());
            List list = this.repository.getFirstUseProductDetail(financeCode);
            map.put("rates", list);
            int id = (int) map.get("金融编号");
            map.put("适用车型", this.repository.getProductSuitableCarList(id));
        }

        return page;
    }

    @Override
    public PageData getFailReasonList(String permit, GetFailReasonListRequest request) {
        return this.repository.getFailReasonList(permit, request.permissionCode, request.getPageSize(), request.getPageIndex());
    }

    @Override
    public PageData getPlanList(String permit, String orderId) {
        return this.repository.getPlanList(permit, orderId);
    }

    @Override
    public Lsh金融设置Model getProductById(int id) {
        return this.lsh金融设置Repository.findOne(id);
    }

    @Override
    @Transactional
    public Lsh金融设置Model saveProduct(Lsh金融设置Model model) {
        Assert.notNull(model);
        return this.lsh金融设置Repository.save(model);
    }

    @Override
    @Transactional
    public boolean saveFailReasonStatus(int id, String status) {
        Assert.hasLength(status);
        int result = this.lsh金融战败原因Repository.set启用状态By金融战败原因编号(id, status);
        return true;
    }

    @Override
    @Transactional
    public boolean saveFinanceChargeList(List<Lsh金融机构设置Model> modelList) {
        if (modelList == null) {
            return true;
        }
        String dealerBrand =null;
        String areaPermit = null;
        boolean flag = false;
        if(modelList!=null&&modelList.size()>0){
            String permit = modelList.get(0).get许可();
            GroupAreaModel groupAreaModel = groupAreaRepository.getInfoByPermit(permit);
            if(groupAreaModel.getIsDealer()==1){
                areaPermit = groupAreaRepository.getParentPermitByPermit(permit);
                flag = true;
                dealerBrand = groupAreaModel.getBrand();
            }
        }


        for (Lsh金融机构设置Model model : modelList) {
            Integer id = model.get金融机构编号();
            List<Lsh金融机构手续费Model> chargeList = model.getLsh金融机构手续费List();
            //List<Lsh金融季度额外奖励Model> bonusList = model.getLsh金融季度额外奖励List();
            if(flag){
                model.setBrand(dealerBrand);
                model.setApplicableArea(areaPermit);
                model.setApplicableStore(model.get许可());
            }
            Lsh金融机构设置Model institution;
            model.set更新时间(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date()));
            institution = lsh金融机构设置Repository.save(model);
            /*if (id == null) {
                institution = this.lsh金融机构设置Repository.save(model);
            } else {
                Lsh金融机构设置Model institution2 = this.lsh金融机构设置Repository.getOne(id);
                institution2.set金融机构(model.get金融机构());
                institution2.setBrand(model.getBrand());
                institution2.setApplicableArea(model.getApplicableArea());
                institution2.setApplicableStore(model.getApplicableStore());
                institution2.set更新账号(model.get更新账号());
                institution2.set更新时间(DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date()));
                institution2.set状态(model.get状态());
                institution2.set许可(model.get许可());
                institution2.setType(model.getType());
                institution = lsh金融机构设置Repository.save(institution2);

            }*/
            if (chargeList != null) {
                chargeList.forEach(it -> {
                    it.set金融机构编号(institution.get金融机构编号());
                    it.set更新账号(institution.get更新账号());
                });

                chargeList = this.lsh金融机构手续费Repository.save(chargeList);
            }

            /*if (bonusList != null) {
                bonusList.forEach(it -> {
                    it.set金融机构编号(institution.get金融机构编号());
                });

                bonusList = this.lsh金融季度额外奖励Repository.save(bonusList);
            }*/
        }
        return true;
    }

    @Override
    public List getFinanceOrg(String permissionCode) {
        return repository.getFinanceOrg(permissionCode,"");
    }

    @Override
    public List getApplicableFinanceOrg(String permissionCode) {
        GroupAreaModel groupAreaModel = groupAreaRepository.getInfoByPermit(permissionCode);
        if(groupAreaModel.getIsDealer()==0)
            return repository.getApplicableFinanceOrgByArea(permissionCode);
        else{
            String parentPermit = groupAreaRepository.getParentPermitByPermit(permissionCode);
            List<Map> list = repository.getFinanceOrg(permissionCode,parentPermit);
            return list.stream()
                    .filter(e->e.get("适用区域")==null||e.get("适用区域").toString().equals("")||(e.get("适用区域").toString().equals(parentPermit)&&(e.get("适用单店")==null||e.get("适用单店").toString().equals("")||e.get("适用单店").toString().equals(permissionCode))))
                    .collect(Collectors.toList());
        }
    }

    @Override
    @Transactional
    public List<Lsh金融设置Model> saveProductBatch(List<Lsh金融设置Model> modelList) {
        Assert.notNull(modelList);
        return this.lsh金融设置Repository.save(modelList);
    }

    @Override
    public Object getFinanceInfoByID(int id) {
        return this.repository.getFinanceInfoByID(id);
    }

    @Override
    public Map getStatisticsNumber(String permissionCode) {
        return this.repository.getStatisticsNumber(permissionCode);
    }

    @Override
    @Transactional
    public List<报价金融表Model> savePlanList(int orderId, List<报价金融表Model> modelList) {
        Assert.notNull(modelList);

        List<报价金融表Model> result = this.报价金融表Repository.save(modelList);
        Integer ida = result.size() > 0 ? result.get(0).get金融编号() : null;
        Integer idb = result.size() > 1 ? result.get(1).get金融编号() : null;
        Integer idc = result.size() > 2 ? result.get(2).get金融编号() : null;
        this.报价单表Repository.set金融AAnd金融BAnd金融CBy报价编号(orderId, ida, idb, idc);
        return result;
    }

    @Override
    @Transactional
    public boolean saveOrderFailReason(int orderId, Integer reasonId) {
        int result = this.报价单表Repository.set金融战败原因编号By报价编号(orderId, reasonId);
        return result > 0;
    }

    @Override
    public List getFinanceProductListBySeries(String permit, GetFinanceProductListBySeriesRequest request) {
        List resList = this.repository.getFinanceProductListBySeries(permit, request.series);

        for (Object data : resList) {
            Map map = (Map) data;
//            int financeCode = Integer.parseInt(map.get("金融编号").toString());
            int id = (int) map.get("金融编号");
            map.put("适用车型", this.repository.getProductSuitableCarList(id));
        }

        return resList;
    }

    @Override
    public List<Lsh先享后选设置Model> saveFirstUseSettings(List<Lsh先享后选设置Model> modelList) {
        Assert.notNull(modelList);
        return this.lsh先享后选设置Repository.save(modelList);
    }

    @Override
    @Transactional
    public boolean delProduct(int id) {
        int result = this.lsh金融设置Repository.delBy产品编码(id);
        return result > 0;
    }

    @Override
    @Transactional
    public Lsh金融申请Model saveFinanceApply(Lsh金融申请Model model) {
        Assert.notNull(model);
        return this.lsh金融申请表Repository.save(model);
    }

    @Override
    public List getFinaceProUpdateInfo(String permit) {
        return repository.getFinaceProUpdateInfo(permit);
    }

    @Override
    public List getFinaceInstitutionPoundage(String permit) {
        return repository.getFinaceInstitutionPoundage(permit);
    }

    @Override
    public List getFinaceCodeByFinaceProCode(String proCode, String permit) {
        return repository.getFinaceCodeByFinaceProCode(proCode, permit);
    }

    @Override
    public ResultData getfinancialorgsAnddetailone(String permit, getfinancialFailAllListitemtwo re) {
        ResultData resl = new ResultData();
        String flag = "";
        String msg = "";
        List nolist31 = new ArrayList();
        List nolist3 = new ArrayList();
        PageData result = new PageData(nolist31, nolist31.size());
        List peak = new ArrayList();
        Map park = new HashMap();
        Map james = new HashMap();
        Map james2 = new HashMap();
        StringBuilder ss = new StringBuilder("");
        try {
            nolist31 = this.repository.getFinancialdetailoneByOrgs(re.moneyorgina, permit);
            if (nolist31 != null) {
                for (int i = 0; i < nolist31.size(); i++) {

                    james = (Map) nolist31.get(i);
                    if (nolist31.size() == 1) {
                        ss.append(james.get("产品编码").toString());
                    } else if (i == nolist31.size() - 1) {
                        ss.append(james.get("产品编码").toString());
                    } else {
                        ss.append(james.get("产品编码").toString() + ",");
                    }
                }
                nolist3.add(ss.toString());
            } else {
                result.setTotal(0);
            }
            msg = ss.toString();
            flag = flag + "true";
            result.setData(nolist3);
            result.setTotal(nolist3.size());
        } catch (Exception var11) {
            logger.error("获取金融机构异常", var11);
            msg = msg + "出错了";
            flag = flag + "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;
    }


    @Override
    public ResultData getfinancialorgsAnddetailtwo(String permit, getfinancialFailAllListitemtwo re) {
        ResultData resl = new ResultData();
        String flag = "";
        String msg = "";
        List nolist31 = new ArrayList();
        PageData result = new PageData(nolist31, nolist31.size());
        List peak = new ArrayList();
        Map park = new HashMap();

        try {
            nolist31 = this.repository.getFinaceProductDetail(re.moneyorgina, permit, re.name);
            if (nolist31 != null) {
                msg = msg + "查询出来了";
            } else {
                msg = "查询的结果为null";
                result.setTotal(0);
            }

            flag = flag + "true";

            if (nolist31 != null && nolist31.size() > 0) {
                result.setData(nolist31);

            } else {
                result.setTotal(0);
            }
        } catch (Exception e) {
            logger.error("金融产品查询错误", e);
            msg = msg + "出错了";
            flag = flag + "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;
    }

    @Override
    public ResultData getSingleLoanClientFinancial(getfinancialFailAllListitemtwothreeforss re, String postman, String permit) {
        ResultData resl = new ResultData();
        List nolist3 = new ArrayList();
        PageData result = new PageData(nolist3, nolist3.size());
        String flag = "";
        String msg = "";
        try {
            nolist3 = repository.getSingleLoanClientFinancial(re.chushibaojiabianhao, permit, postman);

            result.setData(nolist3);
            result.setTotal(nolist3.size());
            msg = msg + "有信息";
            flag = flag + "true";
        } catch (Exception var11) {
            logger.error("数据获取异常。", var11);
            msg = msg + "出错了";
            flag = flag + "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;
    }

    @Override
    public ResultData getSingleLoanClientFinancialAndGift(getfinancialFailAllListitemtwothreeforss re, String postman, String permit) {
        ResultData resl = new ResultData();
        ArrayList nolist3 = new ArrayList();
        PageData result = new PageData(nolist3, nolist3.size());
        List sonnewmodel = null;
        String flag = "";
        String msg = "";
        new ArrayList();

        try {
            List<金融礼物表Model> liwulist = 金融礼物表repository.findByActCodeproinfos(re.chushibaojiabianhao);

            flag = "true";
            result.setData(liwulist);

        } catch (Exception e) {
            logger.error("数据获取异常。", e);

            // logger.error("保存礼物及礼物数异常", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        resl.setMessage(msg);
        resl.setResult(flag);
        resl.setPageData(result);
        return resl;
    }

    @Override
    public List getFirstUseProUpdateInfo(String permit) {
        return repository.getFirstUseProUpdateInfo(permit);
    }

    @Override
    public PageData getFirstUseProduct(GetFirstUseProductListRequest request) {
        return repository.getFirstUseProduct(request);
    }

    @Override
    public boolean getHotLeverByCondition(GetHotLeverByConditionRequest request) {
        boolean flag;
        try {
            List list = repository.getHotLeverByCondition(request);
            if (null != list && list.size() > 0) {
                flag = true;
            } else {
                flag = false;
            }
        } catch (Exception e) {
            logger.error("数据获取异常。", e);
            flag = false;
        }
        return flag;
    }

    @Override
    public boolean checkFinanceProduceIfExit(String financeProName) {
        return repository.checkFinanceProduceIfExit(financeProName);
    }

    @Override
    public boolean saveOrUpdXXHXFinanceSet(SaveOrUpdXXHXFinanceSetInfo request) {
        boolean flag;
        Integer maxFinanceNum = 0;//最大金融编号
        Lsh金融设置Model lsh金融设置Model = new Lsh金融设置Model();
        try {
            //根据传入 金融机构编号  参数判断是否为新增
            if (null != request.金融编号 && "" != request.金融编号.toString()) {
                // 第一步  修改LSH金融设置
                Lsh金融设置Model finaceSetModel = lsh金融设置Repository.findOne(request.金融编号);
                if (!Strings.isNullOrEmpty(request.客户类别)) {
                    finaceSetModel.set客户类别(request.客户类别);
                }
                if (!Strings.isNullOrEmpty(request.开始日期.toString())) {
                    finaceSetModel.set开始日期(request.开始日期);
                }
                if (!Strings.isNullOrEmpty(request.结束日期.toString())) {
                    finaceSetModel.set结束日期(request.结束日期);
                }
                if (!Strings.isNullOrEmpty(request.是否有效)) {
                    finaceSetModel.set是否有效(request.是否有效);
                }
                if (null != request.最低首付比例) {
                    finaceSetModel.set最低首付比例(request.最低首付比例);
                }
                if (null != request.保证金比例) {
                    finaceSetModel.set保证金比例(request.保证金比例);
                }
                if (!Strings.isNullOrEmpty(request.期数)) {
                    finaceSetModel.set期数(request.期数);
                }
                if (!Strings.isNullOrEmpty(request.备注)) {
                    finaceSetModel.set备注(request.备注);
                }
                if (!Strings.isNullOrEmpty(request.金融系列)) {
                    finaceSetModel.set金融系列(request.金融系列);
                }
                if (null != request.金融机构编号) {
                    finaceSetModel.set金融编号(request.金融机构编号);
                }
                if (!Strings.isNullOrEmpty(request.更新账号)) {
                    finaceSetModel.set更新账号(request.更新账号);
                }
                finaceSetModel.set是否删除("否");
                finaceSetModel.set许可("LSH");
                lsh金融设置Repository.save(finaceSetModel);
                maxFinanceNum = request.金融编号;
            } else {
                // 第一步  新增LSH金融设置
                lsh金融设置Model.set按揭类型(request.按揭类型);
                lsh金融设置Model.set开始日期(request.开始日期);
                lsh金融设置Model.set结束日期(request.结束日期);
                lsh金融设置Model.set是否有效(request.是否有效);
                lsh金融设置Model.set最低首付比例(request.最低首付比例);
                lsh金融设置Model.set保证金比例(request.保证金比例);
                lsh金融设置Model.set期数(request.期数);
                lsh金融设置Model.set备注(request.备注);
                lsh金融设置Model.set金融系列(request.金融系列);
                lsh金融设置Model.set是否删除("否");
                lsh金融设置Model.set许可("LSH");
                lsh金融设置Model.set按揭类型("先享后选");
                lsh金融设置Model.set金融机构编号(request.金融机构编号);
                lsh金融设置Model.set更新账号(request.更新账号);
                lsh金融设置Repository.save(lsh金融设置Model);
                //第二步  查出  最大金融号
                List list = repository.getMaxFinanceNum();
                Map map = (Map) list.get(0);
                maxFinanceNum = (Integer) map.get("金融编号");
            }
            //第三步 删除  金融编号为 maxFinanceNum 的记录，然后批量插入 -LSH金融设置适用车型
            String[] syCarType = request.适用车型.split(",", -1);
            lsh金融设置适用车型Repository.deleteByFinanceNum(maxFinanceNum);
            Lsh金融设置适用车型Model model = new Lsh金融设置适用车型Model();
            model.set金融编号(maxFinanceNum);
            for (int i = 0; i < syCarType.length; i++) {
                model.set适用车型(Integer.parseInt(syCarType[i]));
                lsh金融设置适用车型Repository.save(model);
            }
            //第四步   插入或修改 LSH先享后选设置  记录
            String[] nlvStr = request.年利率.split(",", -1);
            String[] bzStr = request.保值金额.split(",", -1);

            String[] canshu = new String[]{"15", "20", "25"};
            for (int j = 0; j < canshu.length; j++) {
                Lsh先享后选设置Model model2 = new Lsh先享后选设置Model();
                if (!Strings.isNullOrEmpty(request.期数)) {
                    model2.set期数(Integer.parseInt(request.期数));
                }
                model2.set更新账号(request.更新账号);
                if (!Strings.isNullOrEmpty(nlvStr[j])) {
                    model2.set年利率(nlvStr[j]);
                }
                if (!Strings.isNullOrEmpty(bzStr[j])) {
                    model2.set保值金额(Integer.parseInt(bzStr[j]));
                }
                model2.set金融编号(maxFinanceNum);
                model2.set参数(Integer.valueOf(canshu[j]));
                Lsh先享后选设置Model lsh先享后选设置Model = lsh先享后选设置Repository.ifExitByNumAndSet(canshu[j], maxFinanceNum);
                if (null == lsh先享后选设置Model) {
                    //新增
                    model2.set租购编号(0);
                    lsh先享后选设置Repository.save(model2);
                } else {
                    //修改
                    if (!Strings.isNullOrEmpty(request.期数)) {
                        lsh先享后选设置Model.set期数(Integer.parseInt(request.期数));
                    }
                    if (!Strings.isNullOrEmpty(request.更新账号)) {
                        lsh先享后选设置Model.set更新账号(request.更新账号);
                    }
                    if (!Strings.isNullOrEmpty(nlvStr[j])) {
                        lsh先享后选设置Model.set年利率(nlvStr[j]);
                    }
                    if (!Strings.isNullOrEmpty(bzStr[j])) {
                        lsh先享后选设置Model.set保值金额(Integer.parseInt(bzStr[j]));
                    }
                    lsh先享后选设置Repository.save(lsh先享后选设置Model);
                }
            }
            flag = true;
        } catch (Exception e) {
            logger.error("保存金融数据异常。", e);
            flag = false;
        }

        return flag;
    }

    @Override
    public boolean delLSHFinanceSYCarType(Integer financeNum) {
        boolean flag;
        try {
            lsh金融设置适用车型Repository.deleteByFinanceNum(financeNum);
            //修改 lsh金融设置  对应记录的 是否删除为 '是'
            lsh金融设置Repository.updIfDelStatuToYes(financeNum);
            flag = true;
        } catch (Exception e) {
            logger.error("删除金融数据异常。", e);
            flag = false;
        }

        return flag;
    }

    @Override
    public ResultData saveOrUpdLshFinanceByPermitAndProNum(SaveOrUpdXXHXFinanceSetInfo request) {
        Integer maxFinanceNum;//最大金融编号
        Lsh金融设置Model lsh金融设置Model = new Lsh金融设置Model();
        try {
            if (null != request.许可 && !"".equals(request.许可) && !"".equals(request.产品编码) && !"".equals(request.产品编码)) {
                List<Map> areaList = repository.getAreaAndStorefoById(request.金融机构编号);
                if(areaList!=null&&areaList.size()>0){
                    Map map = areaList.get(0);
                    request.品牌 = map.get("brand").toString();
                    if(StringUtils.isNotNullOrBlank(map.get("区域编号"))) {
                        request.适用区域 = Integer.parseInt(map.get("区域编号").toString());
                    }
                    int parentId;
                    if(request.适用单店==null ||request.适用单店 ==0){ //经销商登录
                        parentId = groupAreaRepository.getParentIdByPermit(request.许可);
                    }else { //区域选择了单店
                        parentId = groupAreaRepository.getParentIdById(request.适用单店);
                    }

                    if (!(request.适用单店==null ||request.适用单店 ==0)) {  // 不是经销商
                        if(StringUtils.isNotNullOrBlank(request.适用区域)) {
                            if (request.适用区域 != parentId) {
                                return new ResultData("false", "金融产品编码:" + request.产品编码 + ",适用单店不在当前区域内,无法保存");
                            }
                        }else{
                            request.适用区域 = parentId;
                        }
                    }
                }
                //首先，判断条数是否唯一,不唯一则删
                int total = lsh金融设置Repository.getCountByPermitAndProNum(request.许可, request.产品编码);
                while (total > 1) {
                    Integer maxID = lsh金融设置Repository.getMaxIdByPermitAndProNum(request.许可, request.产品编码);
                    lsh金融设置Repository.updIfDelStatuToYes(maxID);
                    total = lsh金融设置Repository.getCountByPermitAndProNum(request.许可, request.产品编码);
                }

                // 第一步  修改LSH金融设置
                Lsh金融设置Model finaceSetModel = lsh金融设置Repository.findByPermitAndProNum(request.许可, request.产品编码);
                if (null == finaceSetModel) {//新增
                    lsh金融设置Model.setSi编码(request.si编码);
                    lsh金融设置Model.set产品编码(request.产品编码);
                    lsh金融设置Model.set产品分类(request.产品分类);
                    lsh金融设置Model.set按揭类型(request.按揭类型);
                    lsh金融设置Model.set开始日期(request.开始日期);
                    lsh金融设置Model.set结束日期(request.结束日期);
                    lsh金融设置Model.set是否有效(request.是否有效);
                    lsh金融设置Model.set最低首付比例(request.最低首付比例);
                    lsh金融设置Model.set保证金比例(request.保证金比例);
                    lsh金融设置Model.set期数(request.期数);
                    lsh金融设置Model.set备注(request.备注);
                    lsh金融设置Model.set金融系列(request.金融系列);
                    lsh金融设置Model.set是否删除(request.是否删除);
                    lsh金融设置Model.set金融产品名称(request.金融产品名称);
                    lsh金融设置Model.set金融机构编号(request.金融机构编号);
                    lsh金融设置Model.set更新账号(request.更新账号);
                    lsh金融设置Model.set客户类别(request.客户类别);
                    lsh金融设置Model.set年利率(request.年利率);
                    lsh金融设置Model.set热销级别(request.热销级别);
                    lsh金融设置Model.set是否固定(request.是否固定);
                    lsh金融设置Model.set是否热销(request.是否固定);
                    lsh金融设置Model.set贴息类型(request.贴息类型);
                    lsh金融设置Model.set贴息利率(request.贴息利率);
                    lsh金融设置Model.set贴息利率B(request.贴息利率B);
                    lsh金融设置Model.set许可(request.许可);
                    lsh金融设置Model.set业务类型(request.业务类型);
                    lsh金融设置Model.set最低首付比例(request.最低首付比例);
                    lsh金融设置Model.set最高尾款比例(request.最高尾款比例);
                    lsh金融设置Model.set是否尾款(request.是否尾款);
                    lsh金融设置Model.set贷款类型(request.贷款类型);
                    lsh金融设置Model.set利率状态(request.利率状态);
                    if (request.适用单店 == null || request.适用单店 == 0) { // 经销商适用区域和适用单店设置为null
                        lsh金融设置Model.set适用区域(null);
                        lsh金融设置Model.set适用单店(null);
                    } else {
                        lsh金融设置Model.set适用区域(request.适用区域);
                        lsh金融设置Model.set适用单店(request.适用单店);
                    }
                    lsh金融设置Model.set品牌(request.品牌);
                    lsh金融设置Repository.save(lsh金融设置Model);
                    List list = repository.getMaxFinanceNumT();
                    Map map = (Map) list.get(0);
                    maxFinanceNum = (Integer) map.get("金融编号");
                } else {//修改
                    if (request.适用单店 == null || request.适用单店 == 0) { // 考虑到历史数据，经销商适用区域和适用单店设置为null
                        finaceSetModel.set适用区域(null);
                        finaceSetModel.set适用单店(null);
                    } else {
                        if (null != request.适用区域) {
                            finaceSetModel.set适用区域(request.适用区域);
                        }
                        if (null != request.适用单店) {
                            finaceSetModel.set适用单店(request.适用单店);
                        }
                    }
                    if (!Strings.isNullOrEmpty(request.利率状态)) {
                        finaceSetModel.set利率状态(request.利率状态);
                    }
                    if (!Strings.isNullOrEmpty(request.si编码)) {
                        finaceSetModel.setSi编码(request.si编码);
                    }
                    if (!Strings.isNullOrEmpty(request.产品编码)) {
                        finaceSetModel.set产品编码(request.产品编码);
                    }
                    if (!Strings.isNullOrEmpty(request.产品分类)) {
                        finaceSetModel.set产品分类(request.产品分类);
                    }
                    if (null != request.金融产品名称) {
                        finaceSetModel.set金融产品名称(request.金融产品名称);
                    }
                    if (!Strings.isNullOrEmpty(request.按揭类型)) {
                        finaceSetModel.set按揭类型(request.按揭类型);
                    }
                    if (!Strings.isNullOrEmpty(request.客户类别)) {
                        finaceSetModel.set客户类别(request.客户类别);
                    }
                    if (!Strings.isNullOrEmpty(request.开始日期.toString())) {
                        finaceSetModel.set开始日期(request.开始日期);
                    }
                    if (!Strings.isNullOrEmpty(request.结束日期.toString())) {
                        finaceSetModel.set结束日期(request.结束日期);
                    }
                    if (!Strings.isNullOrEmpty(request.是否有效)) {
                        finaceSetModel.set是否有效(request.是否有效);
                    }
                    if (null != request.最低首付比例) {
                        finaceSetModel.set最低首付比例(request.最低首付比例);
                    }
                    if (null != request.保证金比例) {
                        finaceSetModel.set保证金比例(request.保证金比例);
                    }
                    if (!Strings.isNullOrEmpty(request.期数)) {
                        finaceSetModel.set期数(request.期数);
                    }
                    if (!Strings.isNullOrEmpty(request.备注)) {
                        finaceSetModel.set备注(request.备注);
                    }
                    if (!Strings.isNullOrEmpty(request.金融系列)) {
                        finaceSetModel.set金融系列(request.金融系列);
                    }
                    if (null != request.金融机构编号) {
                        finaceSetModel.set金融机构编号(request.金融机构编号);
                    }
                    if (!Strings.isNullOrEmpty(request.更新账号)) {
                        finaceSetModel.set更新账号(request.更新账号);
                    }
                    if (!Strings.isNullOrEmpty(request.是否删除)) {
                        finaceSetModel.set是否删除(request.是否删除);
                    }
                    if (!Strings.isNullOrEmpty(request.客户类别)) {
                        finaceSetModel.set客户类别(request.客户类别);
                    }
                    if (!Strings.isNullOrEmpty(request.客户类别)) {
                        finaceSetModel.set客户类别(request.客户类别);
                    }
                    if (!Strings.isNullOrEmpty(request.年利率)) {
                        finaceSetModel.set年利率(request.年利率);
                    }
                    if (!Strings.isNullOrEmpty(request.热销级别)) {
                        finaceSetModel.set热销级别(request.热销级别);
                    }
                    if (!Strings.isNullOrEmpty(request.是否固定)) {
                        finaceSetModel.set是否固定(request.是否固定);
                    }
                    if (!Strings.isNullOrEmpty(request.是否热销)) {
                        finaceSetModel.set是否热销(request.是否热销);
                    }
                    if (!Strings.isNullOrEmpty(request.贴息类型)) {
                        finaceSetModel.set贴息类型(request.贴息类型);
                    }
                    if (!Strings.isNullOrEmpty(request.贴息利率)) {
                        finaceSetModel.set贴息利率(request.贴息利率);
                    }
                    if (!Strings.isNullOrEmpty(request.贴息利率B)) {
                        finaceSetModel.set贴息利率B(request.贴息利率B);
                    }
                    if (!Strings.isNullOrEmpty(request.许可)) {
                        finaceSetModel.set许可(request.许可);
                    }
                    if (!Strings.isNullOrEmpty(request.业务类型)) {
                        finaceSetModel.set业务类型(request.业务类型);
                    }
                    if (null != request.最低首付比例) {
                        finaceSetModel.set最低首付比例(request.最低首付比例);
                    }
                    if (null != request.最高尾款比例) {
                        finaceSetModel.set最高尾款比例(request.最高尾款比例);
                    }
                    if (!Strings.isNullOrEmpty(request.贷款类型)) {
                        finaceSetModel.set贷款类型(request.贷款类型);
                    }
                    lsh金融设置Repository.save(finaceSetModel);
                    maxFinanceNum = finaceSetModel.get金融编号();
                }
//				第三步 删除  金融编号为 maxFinanceNum 的记录，然后批量插入 -LSH金融设置适用车型
                String[] syCarType = request.适用车型.split(",", -1);
                lsh金融设置适用车型Repository.deleteByFinanceNum(maxFinanceNum);
                Lsh金融设置适用车型Model model = new Lsh金融设置适用车型Model();
                model.set金融编号(maxFinanceNum);
                for (int i = 0; i < syCarType.length; i++) {
                    model.set适用车型(Integer.parseInt(syCarType[i]));
                    lsh金融设置适用车型Repository.save(model);
                }
                return new ResultData("true",maxFinanceNum.toString());
            } else {
                return new ResultData("false","保存失败");
            }
        } catch (Exception e) {
            logger.error("金融设置保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false","保存失败");
        }
    }

    @Override
    @Transactional
    public ResultData delLSHFinanceSet(DelLSHFinanceSetRequest request) {
        // 判断金融产品是否被使用
        // TODO: 2017/6/15 需求未定

        Lsh金融设置Model m = lsh金融设置Repository.findOne(Integer.parseInt(request.金融编号));
        if (m == null) {
            return new ResultData("false","数据不存在，删除失败！");
        }
        Integer finnum = m.get金融编号();
        lsh金融设置适用车型Repository.deleteByFinanceNum(finnum);
        lsh金融设置Repository.updIfDelStatuToYes(finnum);
        return new ResultData("true","删除成功");
    }

    @Override
    public ResultData getfinancialIdList(String numer, String permit) {
        ResultData resultData = new ResultData();
        List result = repository.getfinancialIdList(numer, permit);
        if (result != null) {
            resultData.setResult("true");
            resultData.setMessage("查询成功");
            resultData.setPageData(new PageData(result, result.size()));
        } else {
            resultData.setResult("false");
            resultData.setMessage("查询失败，传入信息有误");
        }
        return resultData;
    }


    // 获取所有 金融战败的
    public ResultData getFinancialStandardFailList(String permit, RequestBase reb) {

        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "";
        String msg = null;
        try {
            if (permit != null && !"".equals(permit)) {
                result = repository.getFinancialStandardFailList(permit, reb.getPageSize(), reb.getPageIndex());
            }
            msg = "查询成功";
            flag = "true";
            resl.setPageData(result);
        } catch (Exception e) {
            logger.error("查询详细失败", e);
            msg = "查询失败";
            flag = "false";
        }
        resl.setMessage(msg);
        resl.setResult(flag);
        return resl;
    }


    public ResultData getFinancialStandardFailDetailList(String permit, RequestBase reb) {

        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "";
        String msg = null;
        try {
            if (permit != null && !"".equals(permit)) {
                result = repository.getfinancialFailListByPermit(permit, reb.getPageSize(), reb.getPageIndex());
            }
            msg = "查询成功";
            flag = "true";
            resl.setPageData(result);// 赋值
        } catch (Exception e) {
            logger.error("查询详细失败", e);
            msg = "查询失败";
            flag = "false";
        }
        resl.setMessage(msg);
        resl.setResult(flag);
        return resl;
    }


    // insert
    @Transactional
    public ResultData saveFinancialStandardFail(String permit, String user, getfinancialFailitem items) {
        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "";
        String msg = null;
        try {
            if (permit != null && !"".equals(permit)) {

                if (items.failid == null || "".equals(items.failid)) {

                    flag = InsertSave(permit, user, items);
                } else {
                    flag = updateSave(permit, user, items);
                }

            }
            resl.setMessage("保存成功");
            resl.setResult(flag);
            resl.setPageData(result);
        } catch (Exception e) {
            logger.error("战败原因保存失败", e);
            msg = "保存失败";
            flag = "false";
        }

        return resl;
    }

    @Transactional
    private String InsertSave(String permit, String user, getfinancialFailitem items) {
        String flag = "false";
        boolean reasonflag = false;
        try {
            List<Lsh金融战败原因Model> alli = lsh金融战败原因Repository.findAll();
            for (int i = 0; i < alli.size(); i++) {
                Lsh金融战败原因Model sonlist = alli.get(i);
                if ((items.failreason).equals(sonlist.get战败原因())) {
                    // 相同的名称再次保存应返回false
                    // 意思  就是  如果 以前 就有 这个  战败原因，就不用插入
                    reasonflag = true;
                }
            }
            if (!reasonflag) {
                Lsh金融战败原因Model newitems = new Lsh金融战败原因Model();
                Timestamp ts = new Timestamp(System.currentTimeMillis());
                newitems.set创建时间(ts);
                newitems.set启用状态(items.ueringStatus);
                newitems.set战败原因(items.failreason);
                newitems.set更新时间(ts);
                newitems.set更新账号(user);
                newitems.set许可(permit);
                Lsh金融战败原因Model newitemss = lsh金融战败原因Repository.save(newitems);
                if (items.QuasiDefeat != null && "Y".equals(items.QuasiDefeat)) {
                    Lsh金融战败原因附属Model newitem = new Lsh金融战败原因附属Model();
                    newitem.set金融战败原因编号(newitemss.get金融战败原因编号());
                    newitem.set战败分类("准全款");
                 /*   if (items.failreason != null && !"".equals(items.failreason)) {
                        newitem.set战败内容(items.failreason);
                    }*/
                    lsh金融战败原因附属Repository.save(newitem);
                }
                if (items.Defeat != null && "Y".equals(items.Defeat)) {
                    Lsh金融战败原因附属Model newitem1 = new Lsh金融战败原因附属Model();

                    newitem1.set金融战败原因编号(newitemss.get金融战败原因编号());
                    newitem1.set战败分类("金融战败");

                /*    if (items.failreason != null && !"".equals(items.failreason)) {
                        newitem1.set战败内容(items.failreason);
                    }*/
                    lsh金融战败原因附属Repository.save(newitem1);
                }
                flag = "true";
            } else {
                flag = "false";
            }


        } catch (Exception e) {
            logger.error("战败原因保存错误", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = "false";
        }

        return flag;

    }

    @Transactional
    private String updateSave(String permit, String user, getfinancialFailitem items) {
        String flag = "false";
        try {
            Lsh金融战败原因Model newitems = lsh金融战败原因Repository.findOne(Integer.parseInt(items.failid));
            Timestamp ts = new Timestamp(System.currentTimeMillis());
            newitems.set创建时间(ts);
            if (items.ueringStatus != null && !"".equals(items.ueringStatus)) {
                newitems.set启用状态(items.ueringStatus);
            }
            if (items.failreason != null && !"".equals(items.failreason)) {
                newitems.set战败原因(items.failreason);
            }

            newitems.set更新时间(ts);
            newitems.set更新账号(user);
            newitems.set许可(permit);
            Lsh金融战败原因Model newitemss = lsh金融战败原因Repository.save(newitems);

            lsh金融战败原因附属Repository.deleteItemByfk(newitemss.get金融战败原因编号());
            if (items.QuasiDefeat != null && "Y".equals(items.QuasiDefeat)) {
                Lsh金融战败原因附属Model son1 = new Lsh金融战败原因附属Model();
               /* son1.set战败内容(items.failreason);*/
                son1.set金融战败原因编号(newitemss.get金融战败原因编号());
                son1.set战败分类("准全款");
                lsh金融战败原因附属Repository.save(son1);
            }
            if (items.Defeat != null && "Y".equals(items.Defeat)) {
                Lsh金融战败原因附属Model son2 = new Lsh金融战败原因附属Model();
               /* son2.set战败内容(items.failreason);*/
                son2.set金融战败原因编号(newitemss.get金融战败原因编号());
                son2.set战败分类("金融战败");
                lsh金融战败原因附属Repository.save(son2);
            }

            flag = "true";
        } catch (Exception e) {
            logger.error("战败原因保存错误", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = "false";
        }

        return flag;
    }


    @Transactional
    public ResultData updatefinancialFailStatusitem(int ids) {
        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "";
        String msg = null;
        Lsh金融战败原因Model newitemsss = null;
        try {
            Lsh金融战败原因Model newitemss = lsh金融战败原因Repository.findOne(ids);
            if (newitemss.get启用状态() != null && !"".equals(newitemss.get启用状态())) {
                String status = newitemss.get启用状态();
                if (status.equals("停用")) {
                    newitemss.set启用状态("启用");
                } else {
                    newitemss.set启用状态("停用");
                }
                newitemsss = lsh金融战败原因Repository.save(newitemss);
            }
            msg = "更改成功";
            flag = "true";
            List<Lsh金融战败原因Model> dd = new ArrayList();
            dd.add(newitemsss);
            PageData pg = new PageData(dd, dd.size());
            resl.setMessage(msg);
            resl.setResult(flag);
            resl.setPageData(pg);

        } catch (Exception e) {
            logger.error("系统异常。", e);

            msg = "更改失败";
            flag = "false";
            resl.setMessage(msg);
            resl.setResult(flag);
            resl.setPageData(result);
            return resl;

        }
        resl.setMessage(msg);
        resl.setResult(flag);
        return resl;

    }


    // 批量保存 导入的  金融服务费的 数据
    @Transactional
    public ResultData saveFinancialServiceFee(String permit, String postman, List<financialDetailitemList> reli) {
        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "";
        String msg = "";
        Lsh金融服务费Model newitemsss = null;
        int a=0;
        int b=0;
        try {
            if (permit != null && !"".equals(permit)) {
                for (financialDetailitemList items : reli   /*int i = 0; i < reli.size(); i++*/) {
                    String permits = items.permit;
                    Lsh经销商表Model lsh经销商表Model = lsh经销商表Repository.getLshDistributorByPermit(permits);
                    String bigDistrict=lsh经销商表Model.get大区()==null?"":lsh经销商表Model.get大区();
                    String smallDistrict=lsh经销商表Model.get小区()==null?"":lsh经销商表Model.get小区();
                    String city=lsh经销商表Model.get城市()==null?"":lsh经销商表Model.get城市();
                    String province=lsh经销商表Model.get省份()==null?"":lsh经销商表Model.get省份();
                    if (lsh经销商表Model != null && lsh经销商表Model.getBmbs().equals(permits)
                            && bigDistrict.equals(items.bigDistrict==null?"":items.bigDistrict)
                            && smallDistrict.equals(items.smallDistrict==null?"":items.smallDistrict)
                            && city.equals(items.city==null?"":items.city)
                            && province.equals(items.province==null?"":items.province)) {

                        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-01");
                        //  判断季度得出月份
                        String year = items.date.substring(0, 4);
                        String quarter = items.date.substring(4);
                        List<String> months = Lists.newArrayList();
                        if (quarter.equals("Q1")) {
                            months.add("01");
                            months.add("02");
                            months.add("03");
                        } else if (quarter.equals("Q2")) {
                            months.add("04");
                            months.add("05");
                            months.add("06");
                        } else if (quarter.equals("Q3")) {
                            months.add("07");
                            months.add("08");
                            months.add("09");
                        } else if (quarter.equals("Q4")) {
                            months.add("10");
                            months.add("11");
                            months.add("12");
                        }

                        //保存每个月
                        for (String month : months) {
                            String date = year + "-" + month + "-01";
                            //判断库中是否存在
                            java.sql.Date sqlDate = new java.sql.Date(f.parse(date).getTime());
                            Lsh金融服务费Model sonitems = lsh金融服务费Repository.findByPermitAndDate(items.permit, sqlDate);
                            //存在该条数据 则进行修改  否则 新增
                            if (sonitems == null) {
                                sonitems = new Lsh金融服务费Model();
                            }
                            if (items.dealerCount != null && !"".equals(items.dealerCount)) {
                                sonitems.set集团指导值(items.dealerCount);
                            }
                            if (items.dealerCount != null && !"".equals(items.dealerCount)) {
                                sonitems.set经销商指导值(items.dealerCount);
                            }
                            sonitems.set许可(items.permit);//我3.7提  肖3.9冲了  3.16回滚
                            sonitems.set更新账号(postman);
                            sonitems.set日期(sqlDate);
                            Timestamp ts = new Timestamp(System.currentTimeMillis());
                            sonitems.set更新时间(ts);
                            lsh金融服务费Repository.save(sonitems);
                        }
                        a++;
                    }
                    else{
                        b++;
                        msg="许可："+permits+"，"+"经销商："+items.dealerName+"对应大区小区许可信息匹配异常或已删除，请检查！\n"+msg;
                    }
                }
            }
            msg = "保存成功"+a+"条，" +"失败"+b+"条！"+"\n" +msg ;
            flag = "true";
            resl.setMessage(msg);
            resl.setResult(flag);

        } catch (Exception e) {
            logger.error("保存失败", e);

            msg = "保存失败";
            flag = "false";
        }
        resl.setMessage(msg);
        resl.setResult(flag);
        return resl;
    }

    @Override
    public ResultData findfinancialDetailitemList(String permit, findfinancialDetailitemList result, String date) {
        ResultData resultData = new ResultData();
        try {
            //  判断季度得出月份
            String year = date.substring(0, 4);
            String quarter = date.substring(4);
            String month = null;
            if (quarter.equals("Q1")) {
                month = "01";
            } else if (quarter.equals("Q2")) {
                month = "04";
            } else if (quarter.equals("Q3")) {
                month = "07";
            } else if (quarter.equals("Q4")) {
                month = "10";
            }
            String dates = year + "-" + month + "-01";
            PageData pageData = repository.findfinancialDetailitemList(permit, result.city, result.dealerName, result.dealerLogo, result.cityAvgS, result.cityAvgB, result.getPageSize(), result.getPageIndex(), dates);
            resultData.setPageData(pageData);
            resultData.setResult("true");
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("程序异常");
            logger.error("查询金融服务费", e);
        }
        return resultData;
    }

    @Override
    public ResultData getTrackfinancialDetailitem(Dates dates) {
        ResultData resultData = new ResultData();
        try {
            //  判断季度得出月份
            String year = dates.date.substring(0, 4);
            String quarter = dates.date.substring(4);
            List<String> months = Lists.newArrayList();
            if (quarter.equals("Q1")) {
                months.add(year + "-" + "01" + "-01");
                months.add(year + "-" + "02" + "-01");
                months.add(year + "-" + "03" + "-01");
            } else if (quarter.equals("Q2")) {
                months.add(year + "-" + "04" + "-01");
                months.add(year + "-" + "05" + "-01");
                months.add(year + "-" + "06" + "-01");
            } else if (quarter.equals("Q3")) {
                months.add(year + "-" + "07" + "-01");
                months.add(year + "-" + "08" + "-01");
                months.add(year + "-" + "09" + "-01");
            } else if (quarter.equals("Q4")) {
                months.add(year + "-" + "10" + "-01");
                months.add(year + "-" + "11" + "-01");
                months.add(year + "-" + "12" + "-01");
            }

            PageData pageData = repository.getTrackfinancialDetailitem(months, dates.city, dates.dealerName, dates.dealerLogo, dates.cityAvgS, dates.cityAvgB, dates.getPageSize(), dates.getPageIndex());
            resultData.setPageData(pageData);
            resultData.setResult("true");
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("程序异常");
            logger.error("查询金融服务费", e);
        }
        return resultData;
    }

    @Override
    @Transactional
    public ResultData updatefinancialDetailitem(String permit, String userName, financialDetailitemList financial) {
        ResultData resultData = new ResultData();
        try {
            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-01");
            //  判断季度得出月份
            String year = financial.date.substring(0, 4);
            String quarter = financial.date.substring(4);
            List<String> months = Lists.newArrayList();
            if (quarter.equals("Q1")) {
                months.add("01");
                months.add("02");
                months.add("03");
            } else if (quarter.equals("Q2")) {
                months.add("04");
                months.add("05");
                months.add("06");
            } else if (quarter.equals("Q3")) {
                months.add("07");
                months.add("08");
                months.add("09");
            } else if (quarter.equals("Q4")) {
                months.add("10");
                months.add("11");
                months.add("12");
            }
            //保存每个月
            for (String month : months) {
                String date = year + month;
                //判断库中是否存在
                java.sql.Date sqlDate = new java.sql.Date(f.parse(date).getTime());
                Lsh金融服务费Model sonitems = lsh金融服务费Repository.findByPermitAndDate(permit, sqlDate);
                //存在该条数据 则进行修改  否则 新增
                if (sonitems == null) {
                    sonitems = new Lsh金融服务费Model();
                }
                if (financial.companyCount != null && !"".equals(financial.companyCount)) {
                    sonitems.set集团指导值(financial.companyCount);
                }
                if (financial.dealerCount != null && !"".equals(financial.dealerCount)) {
                    sonitems.set经销商指导值(financial.dealerCount);
                }
                sonitems.set许可(permit);
                sonitems.set日期(sqlDate);
                Timestamp ts = new Timestamp(System.currentTimeMillis());
                sonitems.set更新时间(ts);
                lsh金融服务费Repository.save(sonitems);
                resultData.setMessage("修改成功");
                resultData.setResult("true");
            }
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("程序异常");
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            logger.error("修改金融服务费", e);
        }
        return resultData;
    }

    @Override
    @Transactional
    public ResultData addfinancialDetailitem(String permit, String userName, financialDetailitemList financial) {
        ResultData resultData = new ResultData();
        try {

            SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-01");
            java.sql.Date sqlDate = new java.sql.Date(f.parse(financial.date).getTime());
            Lsh金融服务费Model lsh金融服务费Model = lsh金融服务费Repository.findByPermitAndDate(permit, sqlDate);
            resultData.setMessage("值存在");
            resultData.setResult("false");
            if (lsh金融服务费Model == null) {
                lsh金融服务费Model = new Lsh金融服务费Model();

                lsh金融服务费Model.set经销商指导值(financial.dealerCount);
                lsh金融服务费Model.set集团指导值(financial.companyCount);
                lsh金融服务费Model.set更新账号(userName);
                lsh金融服务费Model.set更新时间(new Timestamp(new Date().getTime()));
                lsh金融服务费Model.set许可(permit);
                lsh金融服务费Model.set日期(sqlDate);
                lsh金融服务费Model.set集团指导值(financial.companyCount);
                lsh金融服务费Repository.save(lsh金融服务费Model);
                resultData.setMessage("新增成功");
                resultData.setResult("true");
            }
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("程序异常");
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            logger.error("新增金融服务费", e);
        }
        return resultData;
    }


    // 获取到 anpay
    public ResultData getFinancialAnnualDetailList(String permit, String usename, getfinancialFailAllListitemtwo re, int indexs, int pagesize) {
        // annualpay
        List baojiadanbiao = repository.getFinaceCodeByorderlist(permit);

        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "";
        String msg = null;
        if (baojiadanbiao.size() == 0) {

            msg = "没有金融产品";
            flag = "true";
        } else {

            result = repository.getFinancialAnnualDetailListById(permit, usename, re, indexs, pagesize);
            if (result != null) {
                int des = result.getTotal();
                msg = des + "";
                flag = "true";
                resl.setPageData(result);
            } else {
                msg = "没有anypay金融产品";
                flag = "true";
            }
        }
        resl.setMessage(msg);
        resl.setResult(flag);
        return resl;
    }

    // 获取到 奔驰租赁的
    public ResultData getFinancialBenzDetailList(String permit, String postman, getfinancialFailAllListitemtwo re, int indexs, int pagesize) {

        List baojiadanbiao = repository.getFinaceCodeByorderlist(permit);

        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "";
        String msg = null;
        if (baojiadanbiao.size() == 0) {

            msg = "没有金融产品";
            flag = "true";
        } else {
            result = repository.getFinancialBenzDetailListByUser(permit, postman, re, indexs, pagesize);
            if (result != null) {
                int des = result.getTotal();
                msg = des + "";
                flag = "true";
                resl.setPageData(result);
            } else {
                msg = "没有奔驰租赁金融产品";
                flag = "true";
            }
        }
        resl.setMessage(msg);
        resl.setResult(flag);
        return resl;
    }

    // 获取所有的
    public ResultData getFinancialCommonDetailList(String permit, String postman, getfinancialFailAllListitemtwo re, int indexs, int pagesize) {

        List baojiadanbiao = repository.getFinaceCodeByorderlist(permit);
        int ui = indexs;
        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "";
        String msg = null;
        if (baojiadanbiao == null) {
            msg = "0";
            flag = "false";
        } else {
            result = repository.getFinancialCommonDetailListByUsername(permit, postman, re, indexs, pagesize);
            if (!"".equals(result) && result != null) {
                int des = result.getTotal();
                msg = des + "";
                flag = "true";
                resl.setPageData(result);
            } else {
                msg = "0";
                flag = "true";
            }
        }
        resl.setMessage(msg);
        resl.setResult(flag);
        return resl;


    }

    //0 是普通 1 星时享
    public ResultData getFinancialAnnualDetailSingle(String quoteId) {
        ResultData resl = new ResultData();
        new ArrayList();
        PageData result = new PageData();
        String flag = "true";
        String msg = "1";
        List resultList = new ArrayList();
        Map qishuMap = new HashMap();
        List InitialList = this.repository.getFinancialAnnualDetailSinglebyPermitAndInitial(quoteId);
        if (InitialList != null) {
            if (InitialList.size() > 0) {
                List pingjie = this.repository.getFinancialAnnualDetailSingle(quoteId);
                if (pingjie != null && pingjie.size() > 0) {
                    qishuMap = (Map) pingjie.get(0);

                    String periods = ((Map) qishuMap).get("期数拆分").toString();
                    String monthly = ((Map) qishuMap).get("月供拆分").toString();
                    String numberTotal = ((Map) qishuMap).get("期数编号拆分").toString();
                    String[] q1 = periods.split(",");
                    String[] q2 = monthly.split(",");
                    String[] q3 = numberTotal.split(",");
                    if (q1.length == 4) {
                        ((Map) qishuMap).put("还款结束期1", q1[0]);
                        ((Map) qishuMap).put("还款结束期2", q1[1]);
                        ((Map) qishuMap).put("还款结束期3", q1[2]);
                        ((Map) qishuMap).put("还款结束期4", q1[3]);
                        ((Map) qishuMap).put("还款额1", q2[0]);
                        ((Map) qishuMap).put("还款额2", q2[1]);
                        ((Map) qishuMap).put("还款额3", q2[2]);
                        ((Map) qishuMap).put("还款额4", q2[3]);
                    } else {
                        ((Map) qishuMap).put("还款结束期1", q1[0]);
                        ((Map) qishuMap).put("还款结束期2", "0");
                        ((Map) qishuMap).put("还款结束期3", "0");
                        ((Map) qishuMap).put("还款结束期4", "0");
                        ((Map) qishuMap).put("还款额1", q2[0]);
                        ((Map) qishuMap).put("还款额2", "0");
                        ((Map) qishuMap).put("还款额3", "0");
                        ((Map) qishuMap).put("还款额4", "0");
                    }
                    resultList.add(qishuMap);
                }
            } else {
                // 从 其他 切换 过来 变成 了 annualpay
                List pingjie4 = this.repository.getjordanonetwo(quoteId);
                if (pingjie4 != null && pingjie4.size() > 0) {
                    qishuMap = (Map) pingjie4.get(0);
                    qishuMap.put("金融机构", "奔驰金融");
                }
                resultList.add(qishuMap);
            }
        }

        result.setData(resultList);
        result.setTotal(resultList.size());
        resl.setPageData(result);
        resl.setMessage(msg);
        resl.setResult(flag);
        return resl;

    }

    public ResultData getFinancialBenzSingleIntentionDetail(String quoteId) {
        ResultData resl = new ResultData();
        new ArrayList();
        PageData result = null;
        String flag = "";
        String msg = "1";
        List resultList = new ArrayList();
        List middleList = new ArrayList();
        Map var4 = new HashMap();
        List SingleDetail = this.repository.getSingleBenzDetail(quoteId);
        if (SingleDetail != null) {
            if (SingleDetail.size() > 0) {
                middleList = this.repository.getBenzDetailListByPermit(quoteId);
                var4 = (Map) middleList.get(0);
                resultList.add(var4);
            } else {
                middleList = this.repository.getjamesonethreeandkobeone(quoteId);
                if (middleList.size() > 0) {
                    var4 = (Map) middleList.get(0);
                    var4.put("金融机构", "奔驰租赁");
                    resultList.add(var4);
                }

            }
        }
        result = new PageData(resultList, resultList.size());
        resl.setPageData(result);
        resl.setMessage(msg);
        resl.setResult("true");
        return resl;
    }

    @Override
    public ResultData getFinancialCommonDetailSingle(String quoteId) {
        ResultData resl = null;
        List list = repository.getFinancialCommonDetailSingle(quoteId);
        if (list != null && list.size() > 0) {
            PageData pageData = new PageData(list, 1);
            resl = new ResultData("true", "1", pageData);
        } else {
            resl = new ResultData("true", "0", null);
        }
        return resl;


    }

    // 普通的 修改
    public ResultData saveCommonFinancialOffer(getfinancialFailAllListitemtwothreefors re, String postman, String permit) {
        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "false";
        String msg = "返回信息：";
// 期数 贷款额 服务费 是 报价金融表的
        //添加 金融方案保存 限制条件， 当贷款额为空时， 不允许保存 金融方案  -- 路松 2017.08.25
        if (!StringUtils.isNullOrBlank(re.daikjine)) {
            flag = this.savefinaceinfo(re, postman, permit);
        } else {
            logger.info("初始报价单号:" + re.chushibaojiabianhao + ",金融编号:" + re.finaceid + ",报价方案的贷款额为空");
        }

        if ("false".equals(flag)) {
            resl.setResult("false");
            resl.setMessage("报价方案保存失败");
            return resl;
        } else {
            Map<String, String> map = this.repository.getClientInfoAndMsgBypermit(permit, re.chushibaojiabianhao);
            String sc = map.get("销售顾问");
            String cus = map.get("顾客姓名");
            String sex = map.get("称谓");
            String cell = map.get("电话号码");
            String msg_content = MessageContext.getCommonFinancialOffer(cus, sex, cell);
            LshMsgUtils.getLshMsg(permit, postman, null, sc, "金融", msg_content, postman, cell);
            List recList = new ArrayList();
            recList.add(sc);
            JPush.sendPushForAndroidAndIos(msg_content, msg_content, null, recList, JPush.Platforms.iTask);
        }

        resl.setMessage(msg);
        resl.setResult(flag);
        resl.setPageData((PageData) result);
        return resl;
    }

    //反按揭激活：金融战败的客户需要金融重新报价
    //modified by 黄永平 需求557
    @Transactional
    public ResultData saveFinanceMortgage(getfinancialFailAllListitemtwothreefors re, String postman, String permit) {
        ResultData resl = new ResultData();

        try {
            Timestamp nowTime = new Timestamp(System.currentTimeMillis());
            Lsh金融申请Model model金融申请 = lsh金融申请表Repository.getApplyFinanceModelByIds(re.chushibaojiabianhao);

            //理论上讲，PC前端只有在有金融申请并且状态是金融战败（04）的情况才能点击反按揭激活按钮
            if (model金融申请 == null) {
                return new ResultData("false", "金融战败后才能反按揭激活");
            } else {
                if (!"04".equals(model金融申请.get状态())) {
                    return new ResultData("false", "金融战败后才能反按揭激活");
                } else {
                    //判断是否能激活：有开票日期并且没有退票日期
                    //获取最新的报价单：是否还原点=是，是否驳回=否
                    List<报价单表Model> list = 报价单表Repository.findModelByRestore(re.chushibaojiabianhao);
                    if (list != null && list.size() > 0) {
                        报价单表Model model报价单表 = list.get(0);
                        if (model报价单表.get交车() != null) {
                            报价交车表Model model报价交车表 = repository报价交车表.findOne(model报价单表.get交车());
                            if (model报价交车表 != null) {
                                if (model报价交车表.get开票时间() != null && model报价交车表.get退票时间() == null) {
                                    model金融申请.set状态("01");//激活
                                    model金融申请.set申请结果日期(null);
                                    model金融申请.set申请日期(null);
                                    model金融申请.set战败原因(null);
                                    model金融申请.set更新账号(postman);
                                    model金融申请.set更新时间(nowTime);
                                    lsh金融申请表Repository.save(model金融申请);
                                } else {
                                    return new ResultData("false", "开票完成后才能反按揭激活");
                                }
                            } else {
                                return new ResultData("false", "开票完成后才能反按揭激活");
                            }
                        } else {
                            return new ResultData("false", "开票完成后才能反按揭激活");
                        }
                    } else {
                        return new ResultData("false", "开票完成后才能反按揭激活");
                    }
                }
            }
            resl.setMessage("反按揭更改成功");
            resl.setResult("true");
            resl.setPageData(null);
        } catch (Exception e) {
            logger.error("反按揭更改失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false", "反按揭更改失败");
        }
        return resl;
    }

    @Transactional
    private String saveFinanceMortgagesAndUser(getfinancialFailAllListitemtwothreefors re, String postman, String permit) {
        String msg = "";
        Timestamp nowtime = new Timestamp(System.currentTimeMillis());
        try {
            Lsh金融申请Model oldmodel = lsh金融申请表Repository.getApplyFinanceModelByIds(re.chushibaojiabianhao);
            oldmodel.set状态("01");
            oldmodel.set申请结果日期(null);
            oldmodel.set申请日期(null);
            oldmodel.set战败原因(null);
            oldmodel.set更新账号(postman);
            oldmodel.set更新时间(nowtime);
            lsh金融申请表Repository.save(oldmodel);
            msg = "true";
        } catch (Exception e) {
            logger.error("反按揭更改失败", e);
            msg = "false";
        }
        return msg;
    }

    // 修改 审批进度 的
    @Override
    @Transactional
    public ResultData saveCommonFinancialAllOfferApprove(getfinancialFailAllListitemtwothreefors re, String postman, String permit) {
        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "true";
        String msg = "返回信息：";
        String reultflag = "";
        //保存审批进度
        try {///
            reultflag = saveCommonFinancialAllOfferApproveAndUser(re, msg, postman, permit);
            if (reultflag.equals("true")) {
                msg = "保存成功";
            } else {
                msg = "保存失败";
            }
            flag = reultflag;


        } catch (Exception e) {
            logger.error("保存总对总审批进度失败", e);
        }
        resl.setMessage(msg);
        resl.setResult(flag);
        resl.setPageData(result);
        return resl;

    }

    // 奔驰租赁的计算器
    public ResultData getBenzCounter(getCounter re, String postman, String permit) {
        ResultData rd = new ResultData();
        PageData pg = new PageData();
        List reList = new ArrayList();
        String flag = "true";
        String msg = "成功";
        // 根据 金融机构 + 车辆编号+ 合同期数+ 年公里数+ 产品类型+ 许可+ 初始报价单号+ 金融编号
        // 类型 1 普通  2 annual  3. 先享后选
        List r1 = new ArrayList();
        if (re.type.equals("3")) {
            // 根据 车型编号 查询出
            Lsh车型Model onmodel = lsh车型Repository.findOne(Integer.parseInt(re.carprice));
            String source = onmodel.get来源();
            String brand = onmodel.get品牌();
            String jibie = onmodel.get级别();
            String carmodel = onmodel.get车型();
            String carmodelDetail = onmodel.get车型详细();
            List<String> listStr = new ArrayList<>();
            listStr.add(source);
            listStr.add(brand);
            listStr.add(jibie);
            listStr.add(carmodel);
            listStr.add(carmodelDetail);
            r1 = repository.getBenzYearRateList(re, permit, listStr);
        }
        rd.setResult(flag);
        rd.setMessage(msg);
        pg.setData(r1);
        pg.setTotal(r1.size());
        rd.setPageData(pg);
        return rd;
    }

    // 返回的一群数据
    public ResultData getBenzCounterFinanceCase(getCounter re, String postman, String permit) {
        ResultData rd = new ResultData();
        PageData pg = new PageData();
        List reList = new ArrayList();
        String flag = "true";
        String msg = "成功";
        List r1 = new ArrayList();
        List r2 = new ArrayList();
        Map endMap = new HashMap();
        List resultList = new ArrayList();
        double baozhije = 0;
        double baozhengje = 0;
        double xiuyangje = 0;
        double yufuje = 0;
        double daikuangje = 0;
        double yuegong = 0;
        double yufubili = 0;
        DecimalFormat df4 = new DecimalFormat("#0.00");
        DecimalFormat df2 = new DecimalFormat("#0.00");
        // 获取车价
        // 根据 车型编号 查询出
        Lsh车型Model onmodel = lsh车型Repository.findOne(Integer.parseInt(re.carprice));
        String source = onmodel.get来源();
        String brand = onmodel.get品牌();
        String jibie = onmodel.get级别();
        String carmodel = onmodel.get车型();
        String carmodelDetail = onmodel.get车型详细();
        List<String> listStr = new ArrayList<>();
        listStr.add(source);
        listStr.add(brand);
        listStr.add(jibie);
        listStr.add(carmodel);
        listStr.add(carmodelDetail);

        r1 = repository.getFinanceRateAndCarId(re.oid, permit, listStr);
        if (r1 != null && r1.size() > 0) {
            Map rMap = new HashMap();
            rMap = (Map) r1.get(0);
            double carSum = 0, msrpValue = 0;
            if (!Strings.isNullOrEmpty(rMap.get("折后价").toString())) {
                carSum = Double.parseDouble(rMap.get("折后价").toString());
                msrpValue = Double.parseDouble(rMap.get("标配MSRP含税").toString());
                if (carSum != 0) {
                    if (re.type.equals("3")) {
                        r2 = repository.getBenzCaseSecond(re, permit, listStr);
                        if (r2 != null && r2.size() > 0) {
                            Map remaps = (Map) r2.get(0);
                            String yearRate = remaps.get("yearRate").toString();
                            String mValue = remaps.get("mValue").toString();//保值比例
                            String gValue = remaps.get("gValue").toString();// 保证比例
                            String productId = remaps.get("productId") == null ? null : remaps.get("productId").toString();
                            String financeId = remaps.get("financeId") == null ? null : remaps.get("financeId").toString();
                            double gdouble = Double.parseDouble(gValue) / 100;
                            double yearRateDouble = Double.parseDouble(yearRate) / 100;
                            if (!mValue.equals("0")) {
                                double mValuedouble = Double.parseDouble(mValue) / 100;
                                if (re.prodectType.equals("1")) {
                                    // 星时享
                                    //baozhije = mValuedouble * carSum;
                                    //Tony修改。修改保值金额公式为:库存标配MSRP含税 * 保值利率
                                    baozhije = mValuedouble * msrpValue;

                                    baozhengje = gdouble * carSum;
                                    yufuje = carSum - baozhije;
                                    yufubili = yufuje / carSum;
                                } else {
                                    yufubili = 0.2;
                                    yufuje = 0.2 * carSum;
                                }
                                daikuangje = carSum - yufuje;
                                double monthRate = yearRateDouble / 12;
                                double sum1 = (monthRate *
                                        (daikuangje *
                                                Math.pow((1 + monthRate),
                                                        Double.parseDouble(re.qishu)
                                                )
                                                - baozhije
                                        )
                                );
                                double sum2 = Math.pow((1 + monthRate), (Double.parseDouble(re.qishu))) - 1;
                                double sum3 = 1 + monthRate;
                                yuegong = sum1 / sum2 / sum3;
                                endMap.put("保值金额", df2.format(baozhije));
                                endMap.put("保证金额", df2.format(baozhengje));
                                endMap.put("修养套餐金额", "0");
                                endMap.put("预付金额", df2.format(yufuje));
                                endMap.put("预付比例", df4.format(yufubili * 100));
                                endMap.put("保值比例", df4.format(mValuedouble * 100));
                                endMap.put("保证比例", df4.format(gdouble * 100));
                                endMap.put("贷款金额", df2.format(daikuangje));
                                endMap.put("金融服务费", "0");
                                endMap.put("月供", df2.format(yuegong));
                                endMap.put("车价", df2.format(carSum));
                                endMap.put("financeId", financeId);
                                endMap.put("productId", productId);
                                resultList.add(endMap);
                            } else {
                                flag = "false";
                                msg = "所选方案不合理，保值比例为空";
                            }
                        } else {
                            flag = "false";
                            msg = "所选方案不合理，无法查出该方案";
                        }
                    }
                }
            } else {
                flag = "false";
                msg = "车型编号不正确，无法查出车价";
            }
        }
        rd.setResult(flag);
        rd.setMessage(msg);
        pg.setData(resultList);
        pg.setTotal(resultList.size());
        rd.setPageData(pg);
        return rd;
    }

    public Map getBenzCounterMonthMoney(getCounter re, String postman, String permit) {
        Map remap = new HashMap();

        double yuegong = 0;
        double yufubili = 0;
        DecimalFormat df2 = new DecimalFormat("#0.00");
        // 年利率
        double yearRateDouble = Double.parseDouble(re.yearRate) / 100;
        // 期数
        double qishuDouble = Double.parseDouble(re.qishu);
        // 月利率
        double monthRate = yearRateDouble / 12;
        // 保值金额
        double baozhije = Double.parseDouble(re.baozhije);
        // 贷款金额
        double daikuangje = Double.parseDouble(re.daikuanje);

//[ 月利率×（贷款本金 ×（1+月利率）^还款总期数 - 保值金额）]÷
//        [（1+月利率）^还款总期数-1]    ÷    (1+月利率*1)
        double sum1 = (monthRate *
                (daikuangje * Math.pow((1 + monthRate), qishuDouble)
                        - baozhije
                )
        );
        double sum2 = Math.pow((1 + monthRate), qishuDouble) - 1;
        double sum3 = 1 + monthRate;
        yuegong = sum1 / sum2 / sum3;
        remap.put("月供", df2.format(yuegong));

        return remap;
    }

    // 这是 奔驰租赁的 保存
    public ResultData saveBenzFinancialOfferAndScheme(getfinancialFailAllListitemtwothreefors re, String postman, String permit) {
        ResultData resl = new ResultData();
        Object result = null;
        String flag = "";
        String msg = "返回信息：";
        //添加 金融方案保存 限制条件， 当贷款额为空时， 不允许保存 金融方案  -- 路松 2017.08.25
        if (!StringUtils.isNullOrBlank(re.daikjine)) {
            flag = this.savefinaceinfotwobenz(re, msg, postman, permit);
        } else {
            logger.info("初始报价单号:" + re.chushibaojiabianhao + ",金融编号:" + re.finaceid + ",报价方案的贷款额为空");
        }
        if ("false".equals(flag)) {
            resl.setResult("false");
            resl.setMessage("报价方案保存失败");
            return resl;
        } else {
            Map<String, String> map = this.repository.getClientInfoAndMsgBypermit(permit, re.chushibaojiabianhao);
            String sc = map.get("销售顾问");
            String cus = map.get("顾客姓名");
            String sex = map.get("称谓");
            String cell = map.get("电话号码");

            Lsh消息Model lsh消息Model = new Lsh消息Model();
            lsh消息Model.set发送人(postman);
            lsh消息Model.set电话号码(cell);
            lsh消息Model.setRead(true);
            lsh消息Model.set接收人(sc);
            lsh消息Model.set发送许可(permit);
            lsh消息Model.set是否删除("否");
            lsh消息Model.set消息分类("金融");
            lsh消息Model.set附属Id类型("金融");
            lsh消息Model.set更新时间(new Timestamp(System.currentTimeMillis()));
            lsh消息Model.set更新账号(postman);
            String msg_content = "客户" + cus + sex + "，电话号码" + cell + "，新车金融报价已完成，请查看。";
            lsh消息Model.set消息内容(msg_content);
            lsh消息Repository.save(lsh消息Model);

            List recList = new ArrayList();
            recList.add(sc);
            JPush.sendPushForAndroidAndIos(msg_content, msg_content, null, recList, JPush.Platforms.iTask);
        }

        resl.setMessage(msg);
        resl.setResult(flag);
        return resl;
    }

    // 这是 anypay的 保存
    public ResultData saveAnnualPayFinanceInfo(getfinancialFailAllListitemtwothreeforss re, String postman, String permit) {
        ResultData resl = new ResultData();
        Object result = null;
        String flag = "";
        String msg = "返回信息：";

        //添加 金融方案保存 限制条件， 当贷款额为空时， 不允许保存 金融方案  -- 路松 2017.08.25
        if (!StringUtils.isNullOrBlank(re.daikuanmoney)) {
            flag = this.saveAnnualPayFinanceInfoAndUser(re, msg, postman, permit);
        } else {
            logger.info("初始报价单号:" + re.chushibaojiabianhao + ",金融编号:" + re.finaceid + ",报价方案的贷款额为空");
        }
        if ("false".equals(flag)) {
            resl.setResult("false");
            resl.setMessage("报价方案保存失败");
            return resl;
        } else {
            Map<String, String> map = this.repository.getClientInfoAndMsgBypermit(permit, re.chushibaojiabianhao);
            String sc = map.get("销售顾问");
            String cus = map.get("顾客姓名");
            String sex = map.get("称谓");
            String cell = map.get("电话号码");
            String msg_content = "客户" + cus + sex + "，电话号码" + cell + "，新车金融报价已完成，请查看。";
            LshMsgUtils.getLshMsg(permit, postman, null, sc, "金融", msg_content, postman, cell, "金融");
            List recList = new ArrayList();
            recList.add(sc);
            JPush.sendPushForAndroidAndIos(msg_content, msg_content, null, recList, JPush.Platforms.iTask);
        }

        resl.setResult(flag);
        resl.setMessage(msg);
        return resl;
    }


    private String saveAnnualPayFinanceInfoAndUser(getfinancialFailAllListitemtwothreeforss re, String msg, String postman, String permit) {

        List chejia = null;
        Map cars = new HashMap();
        String carsprice = "";
        Double cartruep = 0d;
        Double carstar = 0d;
        Double carbaozheng = 0d;
        Double carend = 0d;// 尾款
        Double carevery = 0d; //保证金
        Double feilu = 0d;// 利率 费率
        //Double lilv=0d;
        double carsum = 0;// 月供
        Double daikuangjine = 0d;
        int qishus = 0;

        try {
            // annualpay 中修改了 金融 报价方案的  金融服务费
            if (re.chushibaojiabianhao != null && !"".equals(re.chushibaojiabianhao)) {
                updateServiceFeeFinance(re.chushibaojiabianhao, permit);
            }

            //[ 月利率×（贷款本金 ×（1+月利率）^还款总期数 + 保值金额）]÷[（1+月利率）^还款总期数-1]

            // 需要 添加的

            Lsh金融申请Model statusmodel = lsh金融申请表Repository.getApplyFinanceModelByIds(re.chushibaojiabianhao);
            statusmodel.set状态("02");
            boolean flag = false;
            if (statusmodel != null) {
                if (statusmodel.get更新账号() == null) {
                    //如果 以前的 操作人是 空
                    statusmodel.set更新账号(postman);
                } else {
                    String starman = statusmodel.get更新账号();

                    if (!starman.equals(postman)) {
                         /* 如果 两次操作的 人 不一样，那么 我需要 对 当前操作人 做记录
                           同时 需要 对 修改 的内容 做 记录
                         */
                        saveFinanceShenqingUpdateHositoryLog(statusmodel, postman, re.chushibaojiabianhao);
                        flag = true;

                    }
                }
            }

            Timestamp ts3 = new Timestamp(System.currentTimeMillis());
            statusmodel.set更新账号(postman);
            statusmodel.set更新时间(ts3);
            lsh金融申请表Repository.save(statusmodel);


            报价金融表Model e = (报价金融表Model) this.报价金融表Repository.findOne(re.finaceid);

            if (e != null) {
                if (Strings.isNullOrEmpty(e.get操作人())) {
                    //如果 以前的 操作人是 空
                    e.set操作人(postman);
                    e.set更新账号(postman);
                } else {
                    String starman = statusmodel.get操作人();

                    if (!starman.equals(postman)) {
                         /* 如果 两次操作的 人 不一样，那么 我需要 对 当前操作人 做记录
                           同时 需要 对 修改 的内容 做 记录
                         */
                        saveFinanceUpdatebaojiaHositoryLogs(e, postman, re, re.chushibaojiabianhao);

                    }
                }
            }


            Timestamp ts = new Timestamp(System.currentTimeMillis());
            e.set更新时间(ts);

            // 保存 备注日志 信息
            saveScAndFcDetails(e, re, postman);

            if (re.anjietype != null && !"".equals(re.anjietype)) {
                e.set按揭类型(re.anjietype);
            }

            if (re.rexiaorank != null && !"".equals(re.rexiaorank)) {
                e.set热销级别(re.rexiaorank);
            }

            if (re.finaceorgs != null && !"".equals(re.finaceorgs)) {
                e.set金融机构(re.finaceorgs);
            }

            if (re.statustype != null && !"".equals(re.statustype)) {
                e.set利率状态(re.statustype);
            }

            if (re.statustypesum != null && !"".equals(re.statustypesum)) {
                e.set金融利率(re.statustypesum);
            }

            if (re.daiktype != null && !"".equals(re.daiktype)) {
                e.set贷款类型(re.daiktype);
            }

            if (re.daikuanmoney != null && !"".equals(re.daikuanmoney)) {
                e.set贷款额(re.daikuanmoney);
            }

            if (re.baozhengbili != null && !"".equals(re.baozhengbili)) {
                e.set保证金比例(re.baozhengbili);
            }

            if (re.baozhengjinge != null && !"".equals(re.baozhengjinge)) {
                e.set保证金金额(re.baozhengjinge);
            }

            if (re.trueqishu != null && !"".equals(re.trueqishu)) {
                e.set贷款期数(re.trueqishu);
            }

            if (re.shoufubili != null && !"".equals(re.shoufubili)) {
                e.set首付比例(re.shoufubili);
            }

            if (re.shoufujinge != null && !"".equals(re.shoufujinge)) {
                e.set首付额(re.shoufujinge);
            }

            if (re.weikbili != null && !"".equals(re.weikbili)) {
                e.set尾款比例(re.weikbili);
            }

            if (re.weiikjinge != null && !"".equals(re.weiikjinge)) {
                e.set尾款额(re.weiikjinge);
            }
            //12.17
            if (re.trueqishu != null && !"".equals(re.trueqishu)) {
                e.set贷款期数(re.trueqishu);
            }

            if (re.jingrfuwufee != null && !"".equals(re.jingrfuwufee)) {
                e.set金融服务费(re.jingrfuwufee);
            }
            e.set金融产品编码(re.financePlan);

            e.set月付额(null);
            e.set金融手续费(re.financeFee);
            if (re != null && logger.isDebugEnabled()) {
                Object o = JSONObject.toJSON(e);
                logger.debug(o.toString());
            }
            this.报价金融表Repository.save(e);
            msg = msg + "客户金融信息保存成功";

            报价金融详细表repository.deleteByFinanceNum(re.finaceid);

            deleteInfoAndsiglefinanceId(re);

            return "true";
        } catch (Exception e) {
            msg = msg + "金融保存有错误";
            logger.error("金融保存有错误", e);
            return "false";
        }

    }

    private String deleteInfoAndsiglefinanceId(getfinancialFailAllListitemtwothreeforss re) {
        String flag = "";
        // 使用 integer 接受 会 越界
        try {
            报价金融详细表Model fasonitem1 = new 报价金融详细表Model();
            fasonitem1.set金融编号(re.finaceid);
            fasonitem1.set期数编号(0);

            if (re.qishu1s != null && !"".equals(re.qishu1s)) {
                BigDecimal newpks2 = new BigDecimal(re.qishu1s);
                fasonitem1.set月供(newpks2);
            }

            if (re.qishu1 != null && !"".equals(re.qishu1)) {
                fasonitem1.set期数(Integer.parseInt(re.qishu1));
            }

            this.报价金融详细表repository.save(fasonitem1);

            //@2
            报价金融详细表Model fasonitem2 = new 报价金融详细表Model();
            fasonitem2.set金融编号(re.finaceid);
            fasonitem2.set期数编号(1);

            if (re.qishu2s != null && !"".equals(re.qishu2s)) {
                BigDecimal newpks2 = new BigDecimal(re.qishu2s);
                fasonitem2.set月供(newpks2);
            }

            if (re.qishu2 != null && !"".equals(re.qishu2)) {
                fasonitem2.set期数(Integer.parseInt(re.qishu2));
            }

            this.报价金融详细表repository.save(fasonitem2);

            //@3
            报价金融详细表Model fasonitem3 = new 报价金融详细表Model();
            fasonitem3.set金融编号(re.finaceid);
            fasonitem3.set期数编号(2);

            if (re.qishu3s != null && !"".equals(re.qishu3s)) {
                BigDecimal newpks3 = new BigDecimal(re.qishu3s);
                fasonitem3.set月供(newpks3);
            }

            if (re.qishu3 != null && !"".equals(re.qishu3)) {
                fasonitem3.set期数(Integer.parseInt(re.qishu3));
            }

            this.报价金融详细表repository.save(fasonitem3);

            //4
            报价金融详细表Model fasonitem4 = new 报价金融详细表Model();
            fasonitem4.set金融编号(re.finaceid);
            fasonitem4.set期数编号(3);

            if (re.qishu4s != null && !"".equals(re.qishu4s)) {
                BigDecimal newpks4 = new BigDecimal(re.qishu4s);
                fasonitem4.set月供(newpks4);
            }

            if (re.qishu4 != null && !"".equals(re.qishu4)) {
                fasonitem4.set期数(Integer.parseInt(re.qishu4));
            }

            this.报价金融详细表repository.save(fasonitem4);
            flag = "true";
        } catch (Exception e) {

            logger.error("金融保存有错误", e);
            flag = "false";
        }
        return flag;

    }

    private String savefinaceinfotwobenz(getfinancialFailAllListitemtwothreefors re, String msg, String postman, String permit) {
        List chejia = null;
        Map cars = new HashMap();
        String carsprice = "";
        double cartruep = 0d;
        double carstar = 0d;
        double carbaozheng = 0d;
        double carend = 0d;// 尾款
        double carevery = 0d; //保证金
        double feilu = 0d;// 利率 费率
        //Double lilv=0d;
        double carsum = 0;// 月供
        double baozhengjingetrue = 0d;// 保证 金额
        double baozhijingetrue = 0d;// 保值金额
        double yufubilitrue = 0d;// 预付比例
        double yufujinetrue = 0d;// 预付金额
        double daikuangjinetrue = 0d;
        int qishus = 0;
        try {


            if (!"".equals(re.finaceid) && re.finaceid != null) {
                Lsh金融申请Model statusmodel = lsh金融申请表Repository.getApplyFinanceModelByIds(re.chushibaojiabianhao);

                boolean flag = false;
                if (statusmodel != null) {
                    if (statusmodel.get更新账号() == null) {
                        //如果 以前的 操作人是 空
                        statusmodel.set操作人(postman);
                        statusmodel.set更新账号(postman);

                    } else {
                        String starman = statusmodel.get更新账号();

                        if (!starman.equals(postman)) {
                         /* 如果 两次操作的 人 不一样，那么 我需要 对 当前操作人 做记录
                           同时 需要 对 修改 的内容 做 记录
                         */
                            saveFinanceShenqingUpdateHositoryLog(statusmodel, postman, re.chushibaojiabianhao);
                            flag = true;

                        }
                    }
                }


                statusmodel.set状态("02");
                Timestamp ts3 = new Timestamp(System.currentTimeMillis());
                statusmodel.set更新账号(postman);
                statusmodel.set更新时间(ts3);
                lsh金融申请表Repository.save(statusmodel);
                // 清空那些 从 annualpay 转化过来的 4期数据
                List<报价金融详细表Model> statusmodels = 报价金融详细表repository.findListByComboId(re.finaceid);
                if (statusmodels != null && statusmodels.size() > 0) {
                    报价金融详细表repository.deleteByFinanceNum(re.finaceid);
                }

                报价金融表Model e = this.报价金融表Repository.getLatestfinalMsgs(re.finaceid);
                if (e != null) {
                    Timestamp newmodel1 = new Timestamp(System.currentTimeMillis());
                    e.set更新时间(newmodel1);


                    if (e != null) {
                        if (Strings.isNullOrEmpty(e.get操作人())) {
                            //如果 以前的 操作人是 空
                            e.set操作人(postman);
                            e.set更新账号(postman);
                        } else {
                            String starman = statusmodel.get操作人();

                            if (!starman.equals(postman)) {
                         /* 如果 两次操作的 人 不一样，那么 我需要 对 当前操作人 做记录
                           同时 需要 对 修改 的内容 做 记录
                         */
                                saveFinanceUpdatebaojiaHositoryLog(e, postman, re, re.chushibaojiabianhao);

                            }
                        }
                    }

                    // 保存 备注日志 信息
                    saveScAndFcDetail(e, re, postman);

                    if (re.anjietype != null && !"".equals(re.anjietype)) {
                        e.set按揭类型(re.anjietype);
                    }

                    if (re.rexiaorank != null && !"".equals(re.rexiaorank)) {
                        e.set热销级别(re.rexiaorank);
                    }

                    if (re.finaceorgs != null && !"".equals(re.finaceorgs)) {
                        e.set金融机构(re.finaceorgs);
                    }

                    if (re.statustypesum != null && !"".equals(re.statustypesum)) {
                        e.set金融利率(re.statustypesum);
                    }

                    if (re.foodtype != null && !"".equals(re.foodtype)) {
                        if (re.foodtype.equals("普通")) {
                            e.set产品类型("0");
                        } else {
                            e.set产品类型("1");
                        }

                    }

                    if (re.yeartranssum != null && !"".equals(re.yeartranssum)) {
                        e.set保值参数(re.yeartranssum);
                    }

                    if (re.baozhibili != null && !"".equals(re.baozhibili)) {
                        e.set保值比例(re.baozhibili);
                    }

                    if (re.baozhengmoneybili != null && !"".equals(re.baozhengmoneybili)) {
                        e.set保证金比例(re.baozhengmoneybili);
                    }

                    if (re.xiuyangtaocang != null && !"".equals(re.xiuyangtaocang)) {
                        e.set修养套餐金额(re.xiuyangtaocang);
                    }

                    if (re.shoufubili != null && !"".equals(re.shoufubili)) {
                        e.set首付比例(re.shoufubili);
                    }

                    //修改原因: 当不填写首付比例时， 无法 保存  贷款金额 -- 路松 2017-09-15
                    e.set贷款额(re.daikjine);
                    if (re.daikjine != null && !"".equals(re.daikjine) && !Strings.isNullOrEmpty(re.shoufubili)) {
                        double bili = 100 - Double.parseDouble(re.shoufubili);
                        BigDecimal loanRate = new BigDecimal(Double.toString(bili));
                        BigDecimal one = new BigDecimal("1");
                        String downRateStr = loanRate.divide(one,4,BigDecimal.ROUND_HALF_UP).toString();
                        e.set贷款比例(downRateStr);
                    }

                    if (re.jingrfuwufee != null && !"".equals(re.jingrfuwufee)) {
                        e.set金融服务费(re.jingrfuwufee);
                    }

                   /* if (re.detail != null && !"".equals(re.detail)) {
                        e.set备注(re.detail);
                    }*/

                    if (re.hongtqi != null && !"".equals(re.hongtqi)) {
                        e.set贷款期数(re.hongtqi);
                    }

                    if (re.baozhimoney != null && !"".equals(re.baozhimoney)) {
                        e.set保值金额(re.baozhimoney);
                    }

                    if (re.baozhengjinge != null && !"".equals(re.baozhengjinge)) {
                        e.set保证金金额(re.baozhengjinge);
                    }

                    if (re.shoufujinge != null && !"".equals(re.shoufujinge)) {
                        e.set首付额(re.shoufujinge);
                    }

                    if (re.yuegong != null && !"".equals(re.yuegong)) {
                        e.set月付额(re.yuegong);
                    }

                    //修改原因:金融专员可能推送 自定义 金融方案，这个时候是没有金融编码及产品编码的，所以不做空或null的校验
//                    if (re.financeProductId != null && !"".equals(re.financeProductId)) {
                    e.set金融方案编号(re.financeProductId);
//                    }

                    //修改原因:金融专员可能推送 自定义 金融方案，这个时候是没有金融编码及产品编码的，所以不做空或null的校验
//                    if (re.financeProductNum != null && !"".equals(re.financeProductNum)) {
                    e.set金融产品编码(re.financeProductNum);
//                    }

                    if (re.financeFee != null && !"".equals(re.financeFee)) {
                        e.set金融手续费(re.financeFee);
                    }

                    if (re != null && logger.isDebugEnabled()) {
                        Object o = JSONObject.toJSON(e);
                        logger.debug(o.toString());
                    }
                    this.报价金融表Repository.save(e);
                    msg = msg + "客户金融信息保存成功";
                    return "true";
                } else {

                    报价金融表Model newmodel = new 报价金融表Model();
                    Timestamp ts2 = new Timestamp(System.currentTimeMillis());
                    newmodel.set更新时间(ts2);
                    newmodel.set更新账号(postman);
                    newmodel.set操作人(postman);
                    if (re.anjietype != null && !"".equals(re.anjietype)) {
                        newmodel.set按揭类型(re.anjietype);
                    }

                    if (re.rexiaorank != null && !"".equals(re.rexiaorank)) {
                        newmodel.set热销级别(re.rexiaorank);
                    }

                    if (re.finaceorgs != null && !"".equals(re.finaceorgs)) {
                        newmodel.set金融机构(re.finaceorgs);
                    }

                    if (re.statustypesum != null && !"".equals(re.statustypesum)) {
                        newmodel.set金融利率(re.statustypesum);
                    }

                    if (re.foodtype != null && !"".equals(re.foodtype)) {
                        if (re.foodtype.equals("普通")) {
                            newmodel.set产品类型("0");
                        } else {
                            newmodel.set产品类型("1");
                        }
                    }

                    if (re.yeartranssum != null && !"".equals(re.yeartranssum)) {
                        newmodel.set保值参数(re.yeartranssum);
                    }

                    if (re.baozhibili != null && !"".equals(re.baozhibili)) {
                        newmodel.set保值比例(re.baozhengbili);
                    }

                    if (re.baozhengmoneybili != null && !"".equals(re.baozhengmoneybili)) {
                        newmodel.set保证金比例(re.baozhengmoneybili);
                    }

                    if (re.xiuyangtaocang != null && !"".equals(re.xiuyangtaocang)) {
                        newmodel.set修养套餐金额(re.xiuyangtaocang);
                    }

                    if (re.shoufubili != null && !"".equals(re.shoufubili)) {
                        newmodel.set首付比例(re.shoufubili);
                    }

                    //修改原因: 当不填写首付比例时， 无法 保存  贷款金额 -- 路松 2017-09-15
                    newmodel.set贷款额(re.daikjine);
                    if (!Strings.isNullOrEmpty(re.daikjine) && !Strings.isNullOrEmpty(re.shoufubili)) {
                        DecimalFormat df = new DecimalFormat("######0.00");
                        double ssss = 100 - Double.parseDouble(re.shoufubili);
                        String truenum = df.format(ssss);
                        newmodel.set贷款比例(truenum);

                    }

                    if (re.jingrfuwufee != null && !"".equals(re.jingrfuwufee)) {
                        newmodel.set金融服务费(re.jingrfuwufee);
                    }

                    if (re.detail != null && !"".equals(re.detail)) {
                        newmodel.set备注(re.detail);
                    }

                    if (re.hongtqi != null && !"".equals(re.hongtqi)) {
                        newmodel.set贷款期数(re.hongtqi);
                    }

                    if (re.baozhimoney != null && !"".equals(re.baozhimoney)) {
                        newmodel.set保值金额(re.baozhimoney);
                    }

                    if (re.baozhengjinge != null && !"".equals(re.baozhengjinge)) {
                        newmodel.set保证金金额(re.baozhengjinge);
                    }

                    if (re.baozhengjinge != null && !"".equals(re.baozhengjinge)) {
                        newmodel.set首付额(re.baozhengjinge);
                    }

                    if (re.yuegong != null && !"".equals(re.yuegong)) {
                        newmodel.set月付额(re.yuegong);
                    }

                    if (re.financeProductId != null && !"".equals(re.financeProductId)) {
                        newmodel.set金融方案编号(re.financeProductId);
                    }

                    if (re.financeProductNum != null && !"".equals(re.financeProductNum)) {
                        newmodel.set金融产品编码(re.financeProductNum);
                    }

                    if (re.financeFee != null && !"".equals(re.financeFee)) {
                        newmodel.set金融手续费(re.financeFee);
                    }

                    this.报价金融表Repository.save(newmodel);
                    // 奔驰租赁中修改了 金融服务费
                    if (re.chushibaojiabianhao != null && !"".equals(re.chushibaojiabianhao)) {
                        updateServiceFeeFinance(re.chushibaojiabianhao, permit);
                    }

                    msg = msg + "客户金融信息插入成功";
                    return "true";
                }
            }
        } catch (Exception e) {

            logger.error("金融保存有错误", e);
        }

        return "false";
    }

    // 保存 总对总的  方案的
    @Transactional
    private String savefinaceinfo(getfinancialFailAllListitemtwothreefors re, String postman, String permit) {
        String msg = "";
        try {
            Lsh金融申请Model statusmodel = lsh金融申请表Repository.getApplyFinanceModelByIds(re.chushibaojiabianhao);
            boolean flag = false;
            if (statusmodel != null) {
                if (Strings.isNullOrEmpty(statusmodel.get更新账号())) {
                    //如果 以前的 操作人是 空
                    statusmodel.set操作人(postman);
                    statusmodel.set更新账号(postman);
                } else {
                    String starman = statusmodel.get更新账号();

                    if (!starman.equals(postman)) {
                         /* 如果 两次操作的 人 不一样，那么 我需要 对 当前操作人 做记录
                           同时 需要 对 修改 的内容 做 记录
                         */
                        saveFinanceShenqingUpdateHositoryLog(statusmodel, postman, re.chushibaojiabianhao);
                        flag = true;

                    }
                }
            }
            //修改原因:贷款详细界面 保存金融方案，金融信息会从贷款列表返回潜客列表 --相关bug 5783、5819
            //满足进入金融贷款界面列表条件不修改 状态
            if (!"04".equals(statusmodel.get状态()) && !"06".equals(statusmodel.get状态())
                    && !"07".equals(statusmodel.get状态()) && !"08".equals(statusmodel.get状态())
                    && !"09".equals(statusmodel.get状态()) && !"10".equals(statusmodel.get状态())
                    && !"11".equals(statusmodel.get状态()) && !"13".equals(statusmodel.get状态())
                    && !"14".equals(statusmodel.get状态()) && StringUtils.isNullOrBlank(statusmodel.get退款金额())) {
                if (logger.isDebugEnabled()) {
                    logger.debug("金融潜客保存报价方案，初始报价单号：" + re.chushibaojiabianhao);
                }
                statusmodel.set状态("02");
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug("金融贷款保存报价方案，初始报价单号：" + re.chushibaojiabianhao);
                }
            }
            Timestamp ts3 = new Timestamp(System.currentTimeMillis());
            statusmodel.set更新账号(postman);
            statusmodel.set更新时间(ts3);
            lsh金融申请表Repository.save(statusmodel);

            List<报价金融详细表Model> statusmodels = 报价金融详细表repository.findListByComboId(re.finaceid);


            if (statusmodels != null && statusmodels.size() > 0) {
                报价金融详细表repository.deleteByFinanceNum(re.finaceid);
            }
            报价金融表Model oldmodel = 报价金融表Repository.findOne(re.finaceid);


            // 保存 备注日志 信息
            saveScAndFcDetail(oldmodel, re, postman);

            if (oldmodel != null) {
                if (oldmodel.get操作人() == null) {
                    //如果 以前的 操作人是 空
                    oldmodel.set操作人(postman);
                    oldmodel.set更新账号(postman);
                } else {
                    String starman = statusmodel.get操作人();

                    if (!starman.equals(postman)) {
                         /* 如果 两次操作的 人 不一样，那么 我需要 对 当前操作人 做记录
                           同时 需要 对 修改 的内容 做 记录
                         */
                        saveFinanceUpdatebaojiaHositoryLog(oldmodel, postman, re, re.chushibaojiabianhao);

                    }
                }
            }



            Timestamp ts = new Timestamp(System.currentTimeMillis());
            oldmodel.set更新时间(ts);

            if (re.rexiaorank != null && !"".equals(re.rexiaorank)) {
                oldmodel.set热销级别(re.rexiaorank);
            }
            if (re.finaceorgs != null && !"".equals(re.finaceorgs)) {
                oldmodel.set金融机构(re.finaceorgs);
            }
            if (re.statustype != null && !"".equals(re.statustype)) {
                oldmodel.set利率状态(re.statustype);
            }
            //修改原因: 当不填写首付比例时， 无法 保存  贷款金额 -- 路松 2017-09-15
            oldmodel.set贷款额(re.daikjine);
            if (!Strings.isNullOrEmpty(re.daikjine) && !Strings.isNullOrEmpty(re.shoufubili)) {
                DecimalFormat df = new DecimalFormat("######0.00");
                double truenumDouble = 100 - Double.parseDouble(re.shoufubili);
                String truenumStr = df.format(truenumDouble);
                oldmodel.set贷款比例(truenumStr);
            }
            if (re.statustypesum != null && !"".equals(re.statustypesum)) {
                oldmodel.set金融利率(re.statustypesum);
            }
            if (re.anjietype != null && !"".equals(re.anjietype)) {
                oldmodel.set按揭类型(re.anjietype);
            }

            if (re.shoufujinge != null && !"".equals(re.shoufujinge)) {

                oldmodel.set首付额(re.shoufujinge);
            }

            if (re.shoufubili != null && !"".equals(re.shoufubili)) {

                oldmodel.set首付比例(re.shoufubili);
            }

            if (re.baozhengjinge != null && !"".equals(re.baozhengjinge)) {

                oldmodel.set保证金金额(re.baozhengjinge);
            }

            if (re.baozhengbili != null && !"".equals(re.baozhengbili)) {

                oldmodel.set保证金比例(re.baozhengbili);
            }

            if (re.weiikjinge != null && !"".equals(re.weiikjinge)) {

                oldmodel.set尾款额(re.weiikjinge);
            }
            if (re.weikbili != null && !"".equals(re.weikbili)) {

                oldmodel.set尾款比例(re.weikbili);
            }
            if (re.daiktype != null && !"".equals(re.daiktype)) {

                oldmodel.set贷款类型(re.daiktype);
            }
            //12.17、、、、、、、
            if (re.qishu != null && !"".equals(re.qishu)) {

                oldmodel.set贷款期数(re.qishu);
            }
            if (re.jingrfuwufee != null && !"".equals(re.jingrfuwufee)) {
                oldmodel.set金融服务费(re.jingrfuwufee);
            }
            //月供 肯定 会改成我  下面的 计算公式的  12/20 13:57
            if (re.yuegong != null && !"".equals(re.yuegong)) {

                oldmodel.set月付额(re.yuegong);
            }
            //修改原因:金融专员可能推送 自定义 金融方案，这个时候是没有金融编码及产品编码的，所以不做空或null的校验
            //if (!StringUtils.isNullOrBlank(re.financeProductId)) {
            oldmodel.set金融方案编号(re.financeProductId);
            //}
            //修改原因:金融专员可能推送 自定义 金融方案，这个时候是没有金融编码及产品编码的，所以不做空或null的校验
            //if (!StringUtils.isNullOrBlank(re.financeProductNum)) {
            oldmodel.set金融产品编码(re.financeProductNum);
            //}

            if (!StringUtils.isNullOrBlank(re.financeFee)) {
                oldmodel.set金融手续费(re.financeFee);
            }
            if (re != null) {
                if(logger.isDebugEnabled()) {
                    Object o = JSONObject.toJSON(oldmodel);
                    logger.debug(o.toString());
                }
            }
            报价金融表Repository.save(oldmodel);

            // 总对总中修改了  金融服务费
            if (re.chushibaojiabianhao != null && !"".equals(re.chushibaojiabianhao)) {
                updateServiceFeeFinance(re.chushibaojiabianhao, permit);
            }

            // 期数  没存
            msg = "true";
        } catch (Exception e) {
            msg = "false";
            logger.error("金融保存有错误", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return msg;
    }


    private void saveScAndFcDetail(报价金融表Model oldmodel, getfinancialFailAllListitemtwothreefors re, String postman) {
        // 有点 复杂
        // 现在 传入的 不是空 ，说明 是 销售顾问 写的 鉴于 销售顾问 是 没有 地方查看 专员的修改的 备注的
        //    以前为空， 现在传入的 不是空 ，那么 就是 直接插入 进去   查询 出来的时候  就是联合查询
        if (!Strings.isNullOrEmpty(re.detail)) {
            DetaillogModel newmodel = new DetaillogModel();
            newmodel.setIds(re.chushibaojiabianhao);
            newmodel.set备注(re.detail);
            用户Model nodel = 用户repository.findByCode(postman);
            newmodel.set更新账号(postman);
            if (nodel != null && nodel.get人员姓名() != null) {
                newmodel.set操作人(nodel.get人员姓名());
            } else {
                newmodel.set操作人(postman);
            }

            Timestamp ts = new Timestamp(System.currentTimeMillis());
            newmodel.set日期(ts);
            detaillogModelRepository.save(newmodel);
        }


    }

    private void saveScAndFcDetails(报价金融表Model oldmodel, getfinancialFailAllListitemtwothreeforss re, String postman) {
        // 有点 复杂
        // 现在 传入的 不是空 ，说明 是 销售顾问 写的 鉴于 销售顾问 是 没有 地方查看 专员的修改的 备注的
        //    以前为空， 现在传入的 不是空 ，那么 就是 直接插入 进去   查询 出来的时候  就是联合查询
        if (!Strings.isNullOrEmpty(re.detail)) {
            DetaillogModel newmodel = new DetaillogModel();
            newmodel.setIds(re.chushibaojiabianhao);
            newmodel.set备注(re.detail);
            用户Model nodel = 用户repository.findByCode(postman);
            newmodel.set更新账号(postman);
            if (nodel.get人员姓名() != null) {
                newmodel.set操作人(nodel.get人员姓名());
            } else {
                newmodel.set操作人(postman);
            }

            Timestamp ts = new Timestamp(System.currentTimeMillis());
            newmodel.set日期(ts);
            detaillogModelRepository.save(newmodel);
        }


    }

    // 如果 申请通过后  会 插入到////
    @Transactional
    private String saveCommonFinancialAllOfferApproveAndUser(getfinancialFailAllListitemtwothreefors re, String msg, String postman, String permit) {
        String flag = "true";
        try {
            Timestamp ts = new Timestamp(System.currentTimeMillis());
            if (re.failreason != null && !"".equals(re.failreason)) {
                //  只要 有 战败原因  那么 就是  改成 战败
                flag = saveAllFailReason(re.chushibaojiabianhao, re.failreason, permit, postman);
            } else {

                Lsh金融申请Model oldmodel = lsh金融申请表Repository.getApplyFinanceModelByIds(re.chushibaojiabianhao);
              /*  if(!postman.equals(oldmodel.get操作人())&&oldmodel.get操作人()!=null){
                    flag = "该客户已经被其他专员操作";
                }else {*/

                if (oldmodel.get操作人() != null) {
                    if (!(oldmodel.get更新账号()).equals(postman)) {
                        // 需要 对 日志表 进行 写入
                        saveFinanceShenqingUpdateHositoryLog(oldmodel, postman, re.chushibaojiabianhao);
                    }
                } else {
                    oldmodel.set操作人(postman);
                    oldmodel.set更新账号(postman);
                }
                oldmodel.set更新时间(ts);

                if (re.jingesolestatus1 != null && !"".equals(re.jingesolestatus1)) {

                    String ends = zhuanhuanweishuzi(re.jingesolestatus1);
                    oldmodel.set状态(ends);

                }
                if (re.yixiangdate != null && !"".equals(re.yixiangdate)) {
                    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
                    java.util.Date date2 = formatter2.parse(re.yixiangdate);
                    java.sql.Date sqlDate2 = new java.sql.Date(date2.getTime());

                    SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd");
                    Date date3 = formatter3.parse(re.yixiangdate);
                    java.sql.Date sqlDate3 = new java.sql.Date(date3.getTime());

                    oldmodel.set申请日期(sqlDate3);
                    oldmodel.set抵押日期(null);
                    oldmodel.set状态("08");
                    //申请通过 发送消息
                    sendMsganditaskshenpi(permit, re.chushibaojiabianhao, postman);
                } else {
                    oldmodel.set状态("05");
                    oldmodel.set申请日期(null);
                    oldmodel.set抵押日期(null);
                    oldmodel.set申请结果日期(null);
                    sendMsganditaskshenpifail(permit, re.chushibaojiabianhao, postman);
                }

                oldmodel.set更新账号(postman);
                oldmodel.set更新时间(new Timestamp(new Date().getTime()));
                lsh金融申请表Repository.save(oldmodel);
                // 将数据 保存到 报价金融申请附属
                flag = saveLoanClientDateSum(postman, permit);
            }
           /* }*/

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("金融审批 保存有错误", e);
            flag = "false";
        }
        return flag;
    }

    private void saveFinanceUpdatebaojiaHositoryLog(报价金融表Model oldmodel, String postman, getfinancialFailAllListitemtwothreefors re, String chushibaojiabianhao) {
        报价金融表LogModel newmodel = new 报价金融表LogModel();
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        用户Model modelites = 用户repository.findByCode(postman);
        newmodel.set操作人(modelites.get人员姓名());
        newmodel.setOrgQid(chushibaojiabianhao);
        newmodel.set更新账号(postman);
        newmodel.set更新时间(ts);
        newmodel.set金融编号(oldmodel.get金融编号());
        newmodel.set金融原价(oldmodel.get金融原价());
        newmodel.set金融折后价(oldmodel.get金融折后价());
        newmodel.set金融机构(oldmodel.get金融机构());
        newmodel.set金融利率(oldmodel.get金融利率());
        newmodel.set利率状态(oldmodel.get利率状态());
        newmodel.set保证金比例(oldmodel.get保证金比例());
        newmodel.set保证金金额(oldmodel.get保证金金额());
        newmodel.set首付比例(oldmodel.get首付比例());
        newmodel.set首付额(oldmodel.get首付额());
        newmodel.set贷款比例(oldmodel.get贷款比例());
        newmodel.set贷款额(oldmodel.get贷款额());
        newmodel.set尾款比例(oldmodel.get尾款比例());
        newmodel.set尾款额(oldmodel.get尾款额());
        newmodel.set贷款期数(oldmodel.get贷款期数());
        newmodel.set月付额(oldmodel.get月付额());
        newmodel.set利息总额(oldmodel.get利息总额());
        newmodel.set保值比例(oldmodel.get保值比例());
        newmodel.set保值金额(oldmodel.get保值金额());
        newmodel.set保值参数(oldmodel.get保值参数());
        newmodel.set修养套餐金额(oldmodel.get修养套餐金额());
        newmodel.set金融手续费(oldmodel.get金融手续费());
        newmodel.set金融集团手续费(oldmodel.get金融集团手续费());
        newmodel.set金融服务费(oldmodel.get金融服务费());
        newmodel.set金融服务费折扣(oldmodel.get金融服务费折扣());
        newmodel.set热销级别(oldmodel.get热销级别());
        newmodel.set业务类型(oldmodel.get业务类型());
        newmodel.set按揭类型(oldmodel.get按揭类型());
        newmodel.set产品类型(oldmodel.get产品类型());
        newmodel.set贷款类型(oldmodel.get贷款类型());
        newmodel.set备注(oldmodel.get备注());


        报价金融表LogModelrepository.save(newmodel);
    }

    @Transactional
    private void saveFinanceUpdatebaojiaHositoryLogs(报价金融表Model oldmodel, String postman, getfinancialFailAllListitemtwothreeforss re, String chushibaojiabianhao) {
        报价金融表LogModel newmodel = new 报价金融表LogModel();


        Timestamp ts = new Timestamp(System.currentTimeMillis());

        用户Model modelites = 用户repository.findByCode(postman);
        newmodel.set操作人(modelites.get人员姓名());
        newmodel.setOrgQid(chushibaojiabianhao);
        newmodel.set更新账号(postman);
        newmodel.set更新时间(ts);


        newmodel.set金融编号(oldmodel.get金融编号());
        newmodel.set金融原价(oldmodel.get金融原价());
        newmodel.set金融折后价(oldmodel.get金融折后价());
        newmodel.set金融机构(oldmodel.get金融机构());
        newmodel.set金融利率(oldmodel.get金融利率());
        newmodel.set利率状态(oldmodel.get利率状态());
        newmodel.set保证金比例(oldmodel.get保证金比例());
        newmodel.set保证金金额(oldmodel.get保证金金额());
        newmodel.set首付比例(oldmodel.get首付比例());
        newmodel.set首付额(oldmodel.get首付额());
        newmodel.set贷款比例(oldmodel.get贷款比例());
        newmodel.set贷款额(oldmodel.get贷款额());
        newmodel.set尾款比例(oldmodel.get尾款比例());
        newmodel.set尾款额(oldmodel.get尾款额());
        newmodel.set贷款期数(oldmodel.get贷款期数());
        newmodel.set月付额(oldmodel.get月付额());
        newmodel.set利息总额(oldmodel.get利息总额());
        newmodel.set保值比例(oldmodel.get保值比例());
        newmodel.set保值金额(oldmodel.get保值金额());
        newmodel.set保值参数(oldmodel.get保值参数());
        newmodel.set修养套餐金额(oldmodel.get修养套餐金额());
        newmodel.set金融手续费(oldmodel.get金融手续费());
        newmodel.set金融集团手续费(oldmodel.get金融集团手续费());
        newmodel.set金融服务费(oldmodel.get金融服务费());
        newmodel.set金融服务费折扣(oldmodel.get金融服务费折扣());
        newmodel.set热销级别(oldmodel.get热销级别());
        newmodel.set业务类型(oldmodel.get业务类型());
        newmodel.set按揭类型(oldmodel.get按揭类型());
        newmodel.set产品类型(oldmodel.get产品类型());
        newmodel.set贷款类型(oldmodel.get贷款类型());
        newmodel.set备注(oldmodel.get备注());


        报价金融表LogModelrepository.save(newmodel);
    }

    private void saveFinanceShenqingUpdateHositoryLog(Lsh金融申请Model oldmodel, String postman, String chushibaojiabianhao) {
// xxd
        Lsh金融申请LogModel lsh金融申请表 = new Lsh金融申请LogModel();


        用户Model modelites = 用户repository.findByCode(postman);
        if (modelites != null && modelites.get人员姓名() != null) {
            lsh金融申请表.set操作人(modelites.get人员姓名());
        } else {
            lsh金融申请表.set操作人(postman);
        }

        lsh金融申请表.set更新账号(postman);

        Timestamp ts = new Timestamp(System.currentTimeMillis());
        lsh金融申请表.set更新时间(ts);

        lsh金融申请表.set编号(oldmodel.get编号());
        lsh金融申请表.set初始报价单号(oldmodel.get初始报价单号());

        lsh金融申请表.set状态(oldmodel.get状态());

        lsh金融申请表.set申请日期(oldmodel.get申请日期());
        lsh金融申请表.set申请结果日期(oldmodel.get申请结果日期());
        lsh金融申请表.set准全款原因(oldmodel.get准全款原因());
        lsh金融申请表.set准全款备注(oldmodel.get准全款备注());

        lsh金融申请表.set战败原因(oldmodel.get战败原因());// 战败 原因 保存 前台传入的   如果 有，则是 直接取出编号
        lsh金融申请表.set战败备注(oldmodel.get战败备注());

        // 如果没有  则是直接 保存的是    先插入 战败 原因表 和   战败原因附属 表  之后  生成的  编号
        lsh金融申请表.set撤单日期(oldmodel.get撤单日期());
        lsh金融申请表.set撤单原因(oldmodel.get撤单原因());
        lsh金融申请表.set退款金额(oldmodel.get退款金额());
        lsh金融申请表.set重新申请日期(oldmodel.get重新申请日期());
        lsh金融申请表.set重新申请金融服务费(oldmodel.get重新申请金融服务费());

        lsh金融申请表.set抵押日期(oldmodel.get抵押日期());
        lsh金融申请表.set放款日期(oldmodel.get放款日期());


        lsh金融申请logxxdrepository.save(lsh金融申请表);
    }

    private String saveLoanClientDateSum(String postman, String permit) {
        String flag = "";
        List resultList = repository.getLoanClientDetailByUser(postman, permit);//
        Map msl = new HashMap();
        String kehuxingming = null;
        String ketel = null;
        String chegnwei = null;
        String leixing = null;
        String chushi = null;
        try {
            if (resultList != null) {
                for (int i = 0; i < resultList.size(); i++) {
                    msl = (Map) resultList.get(i);
                    kehuxingming = msl.get("客户姓名").toString();
                    ketel = msl.get("客户电话").toString();
                    chegnwei = msl.get("称谓").toString();
                    leixing = msl.get("客户类型").toString();
                    chushi = msl.get("初始报价单号").toString();
                    Lsh金融申请附属Model sonson = lsh金融申请附属Repository.getFinanceApplyRelyModel(chushi);
                    if (sonson == null) {
                        Lsh金融申请附属Model sonmodel = new Lsh金融申请附属Model();
                        sonmodel.set贷款人类型(leixing);
                        sonmodel.set贷款人姓名(kehuxingming);
                        sonmodel.set更新账号(postman);
                        sonmodel.set初始报价单号(chushi);
                        sonmodel.set贷款人称谓(chegnwei);
                        sonmodel.set贷款人联系电话(ketel);
                        lsh金融申请附属Repository.save(sonmodel);
                    } else {
                        continue;
                    }
                    kehuxingming = null;
                    ketel = null;
                    chegnwei = null;
                    leixing = null;
                }
            }
            flag = "true";
        } catch (Exception e) {

            logger.error("查询失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            flag = "false";
        }
        return flag;
    }

    private String saveAllFailReason(String chushibaojiabianhao, String failreason, String permit, String postman) {
        String flag = "true";
        try {
            Timestamp date = new Timestamp(System.currentTimeMillis());
            Lsh金融申请Model lsh金融申请表 = lsh金融申请表Repository.getApplyFinanceModelByIds(chushibaojiabianhao);
            lsh金融申请表.set状态("04");
            lsh金融申请表.set申请日期(null);
            int reason = getfinancefailreason(failreason, permit, postman);
            lsh金融申请表.set战败原因(reason);// 战败 原因 保存 前台传入的   如果 有，则是 直接取出编号
            // 如果没有  则是直接 保存的是    先插入 战败 原因表 和   战败原因附属 表  之后  生成的  编号
            lsh金融申请表.set抵押日期(null);
            lsh金融申请表.set申请结果日期(null);
            lsh金融申请表.set更新时间(date);
            lsh金融申请表.set准全款备注(null);
            lsh金融申请表.set战败备注(null);
            lsh金融申请表.set更新时间(date);
            lsh金融申请表.set更新账号(postman);
            lsh金融申请表.set操作人(postman);
            lsh金融申请表Repository.save(lsh金融申请表);

            FinanceLogModel savemodel = new FinanceLogModel();
            savemodel.setLogTime(date);
            savemodel.setLogUser(permit);
            savemodel.setState("04");// 金融战败  日志文件
            savemodel.setOrgQsn(chushibaojiabianhao);
            financeLogRepository.save(savemodel);
            sendMsganditaskshenpizhanbai(permit, chushibaojiabianhao, postman);
            flag = "true";
        } catch (Exception e) {
            logger.error("发送出错", e);
            flag = "false";
        }
        return flag;
    }

    private String zhuanhuanweishuzi(String weniz) {
        String end = null;
        if (weniz.equals("汽车金融待报价")) {
            end = "01";
        } else if (weniz.equals("汽车金融报价完成")) {
            end = "02";
        } else if (weniz.equals("准全款潜客")) {
            end = "03";
        } else if (weniz.equals("汽车金融意向确认")) {
            end = "05";
        } else if (weniz.equals("汽车金融战败")) {
            end = "04";
        } else if (weniz.equals("已申请-待批复")) {
            end = "06";
        } else if (weniz.equals("已申请-批复通过")) {
            end = "07";
        } else if (weniz.equals("已申请-批复未通过")) {
            end = "08";
        } else if (weniz.equals("抵押完成")) {
            end = "10";
        } else {
            end = "01";
        }
        return end;
    }

    // 如果 申请通过后  会 插入到
    private void saveshenpifinaceinfopay(getfinancialFailAllListitemtwothreeforss re, String msg, String postman, String permit) {
        try {
            Lsh金融申请Model oldmodel = lsh金融申请表Repository.findOne(re.finaceid);
       /*
            public String yixiangfanan;// 意向方案申请
            public String yixiangdate;// 意向方案日期

            public String shenqingjieguo;// 申请结果
            public String shenqingjieguodate;// 申请结果日期
            public String zhunreason;// 全款原因
            public String failreason;// 战败原因*/
            Timestamp ts = new Timestamp(System.currentTimeMillis());
            oldmodel.set更新时间(ts);
            oldmodel.set更新账号(postman);

            lsh金融申请表Repository.save(oldmodel);
            msg += "客户金融 审批信息保存成功";
        } catch (Exception e) {

            logger.error("金融审批 保存有错误", e);
        }


    }

    //贷款客户的 查询
    public ResultData getLoanClientFinancialList(getfinancialFailAllListitemtwothreeforss re, String postman, String permit) {
        ResultData resl = new ResultData();
        List nolist3 = new ArrayList();
        PageData result = new PageData(nolist3, nolist3.size());

        String flag = "";
        String msg = "";
        //List<Lsh金融申请表Model> nolist=lsh金融申请表Repository.getitemByfkanddetai();    ///以后 会更改 条件
        try {
            //result = repository.getitemByfkanddetai(re, permit, postman, re.getPageIndex(), re.getPageSize());//
            result = repository.getItemByPermitAndId(re, permit, postman, re.getPageIndex(), re.getPageSize());

            msg += "有信息";
            flag += "true";
        } catch (Exception e) {
            logger.error("金融申请详细  获取有错误", e);
            msg += "出错了";
            flag += "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;

    }


    public ResultData saveGiftInfoAndClientInfo(getfinancialDetailitemonesixitem re, String permit, String postman) {
        ResultData resl = new ResultData();
        PageData result = null;
        String flag = "false";
        String msg = "";
        try {

            flag = savePeopleBasicInfoone(re, permit);
            if ("false".equals(flag)) {
                msg = "保存信息失败";
            } else {
                msg = "保存信息成功";
            }
            //saveprofoodinfothree(re, msg);
        } catch (Exception e) {
            logger.error("金融 保存 获取有错误", e);
            msg = "出错了";
            flag = "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;


    }

    private String savePeopleBasicInfoone(getfinancialDetailitemonesixitem re, String permit) {
        String flag = "";
        try {
            Lsh金融申请附属Model newitem = this.lsh金融申请附属Repository.getFinanceApplyRelyModel(re.chushibianhao);
            if (newitem != null) {
                if (re.x1 != null && !"".equals(re.x1)) {
                    newitem.set贷款人类型(re.x1);
                }
                if (!Strings.isNullOrEmpty(re.bDiscount)) {
                    if (re.bDiscount.equals("0")) {
                        BigDecimal zeros = new BigDecimal("0");
                        newitem.set贴息金额(zeros);
                    } else {
                        BigDecimal notzero = new BigDecimal(re.discountAmount);
                        newitem.set贴息金额(notzero);
                    }

                } else {
                    BigDecimal zeros = new BigDecimal("0");
                    newitem.set贴息金额(zeros);
                }
                Timestamp ts = new Timestamp(System.currentTimeMillis());
                newitem.set更新时间(ts);
                newitem.set更新账号(permit);
                if (re.x2 != null && !"".equals(re.x2)) {
                    newitem.set贷款人姓名(re.x2);
                }

                if (re.x3 != null && !"".equals(re.x3)) {
                    newitem.set贷款人称谓(re.x3);
                }

                if (re.x4 != null && !"".equals(re.x4)) {
                    newitem.set贷款人身份证(re.x4);
                }

                if (re.x5 != null && !"".equals(re.x5)) {
                    newitem.set贷款人联系电话(re.x5);
                }

                if (re.x6 != null && !"".equals(re.x6)) {
                    newitem.set贷款人省份(re.x6);
                }

                if (re.x7 != null && !"".equals(re.x7)) {
                    newitem.set贷款人城市(re.x7);
                }

                if (re.x8 != null && !"".equals(re.x8)) {
                    newitem.set贷款人行政区(re.x8);
                }

                if (re.x9 != null && !"".equals(re.x9)) {
                    newitem.set贷款人邮编(re.x9);
                }

                if (re.x10 != null && !"".equals(re.x10)) {
                    newitem.set贷款人详细地址(re.x10);
                }

                if (re.y2 != null && !"".equals(re.y2)) {
                    newitem.set联系人姓名(re.y2);
                }

                if (re.y3 != null && !"".equals(re.y3)) {
                    newitem.set联系人称谓(re.y3);
                }
                if (re.y4 != null && !"".equals(re.y4)) {
                    newitem.set联系人身份证(re.y4);
                }
                if (re.y5 != null && !"".equals(re.y5)) {
                    newitem.set联系人联系电话(re.y5);
                }
                if (re.y6 != null && !"".equals(re.y6)) {
                    newitem.set联系人省份(re.y6);
                }
                if (re.y7 != null && !"".equals(re.y7)) {
                    newitem.set联系人城市(re.y7);
                }
                if (re.y8 != null && !"".equals(re.y8)) {
                    newitem.set联系人行政区(re.y8);
                }
                if (re.y9 != null && !"".equals(re.y9)) {
                    newitem.set联系人邮编(re.y9);
                }
                if (re.y10 != null && !"".equals(re.y10)) {
                    newitem.set联系人详细地址(re.y10);
                }
                lsh金融申请附属Repository.save(newitem);
                flag = "true";
            } else {
                flag = "false";
            }
        } catch (Exception e) {
            logger.error("保存失败", e);
            flag = "false";
        }

        return flag;
    }

    /**
     * 保存金融礼品
     *
     * @param list
     * @param initialNum
     * @param username
     * @return
     */
    public ResultData saveGift(List<GetGift> list, String initialNum, String username) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List<金融礼物表Model> liwulist = 金融礼物表repository.findByActCodeproinfos(initialNum);
            金融礼物表repository.deleteInBatch(liwulist);
            for (GetGift getGift : list) {
                金融礼物表Model model = new 金融礼物表Model();
                model.set初始报价单号(initialNum);
                model.set礼物名称(getGift.gift);
                model.set礼物数量(Integer.parseInt(getGift.giftNum));
                model.set更新账号(username);
                model.set更新时间(new Timestamp(new Date().getTime()));
                金融礼物表repository.save(model);
            }
            resultData.setResult("true");
        } catch (Exception e) {
            logger.error("保存礼物及礼物数异常", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }


    private String zhuanhuanqiantai(String xman) {
        String result = "";
        if (xman.equals("01")) {
            result = "汽车金融待报价";
        } else if (xman.equals("02")) {
            result = "汽车金融报价报价完成";
        } else if (xman.equals("03")) {
            result = "准全款潜客";
        } else if (xman.equals("04")) {
            result = "汽车金融战败";
        } else if (xman.equals("05")) {
            result = "汽车金融意向确认";
        } else if (xman.equals("06")) {
            result = "已申请-待批复";
        } else if (xman.equals("07")) {
            result = "已申请-批复通过";
        } else if (xman.equals("08")) {
            result = "已申请-批复未通过";
        } else if (xman.equals("09")) {
            result = "金融通过后撤单";
        } else if (xman.equals("10")) {
            result = "抵押完成";
        }

        return result;

    }

    //
    public ResultData getLoanClientAndFailMsg(GetFinancePoundageListRequest re, String permit) {
        ResultData resl = new ResultData();

        String flag = "";
        String msg = "";
        List nolist3 = new ArrayList<>();
        PageData result = new PageData(nolist3, nolist3.size());
        List nolist1 = new ArrayList<>();

        Map son4m = new HashMap();
        Map son5m = null;
        try {
            Lsh金融申请Model lsh金融申请表 = lsh金融申请表Repository.getApplyFinanceModelByIds(re.permissionCode);

            String ztai = zhuanhuanqiantai(lsh金融申请表.get状态());
            son4m.put("金融销售状态", ztai);

            if (lsh金融申请表.get申请日期() != null && !"".equals(lsh金融申请表.get申请日期())) {
                son4m.put("意向方案申请", "有");
                son4m.put("意向日期", lsh金融申请表.get申请日期());
            } else {
                son4m.put("意向方案申请", "无");
                son4m.put("意向日期", null);
            }

            if (lsh金融申请表.get申请结果日期() != null && !"".equals(lsh金融申请表.get申请结果日期())) {
                son4m.put("申请结果", "通过");
                son4m.put("申请结果日期", lsh金融申请表.get申请结果日期());
            } else {
                son4m.put("申请结果", "未通过");
                son4m.put("申请结果日期", null);
            }
            if (lsh金融申请表.get准全款原因() != null && !"".equals(lsh金融申请表.get准全款原因())) {

                nolist1 = repository.getstatusbysqls(lsh金融申请表.get准全款原因());///
                if (nolist1.size() > 0) {

                    son5m = (Map) nolist1.get(0);
                    if (son5m.get("d") != null) {
                        son4m.put("准全款原因内容", son5m.get("d").toString());
                        son4m.put("准全款原因", "有");
                    } else {
                        son4m.put("准全款原因", "无");
                        son4m.put("准全款原因内容", null);
                    }
                } else {
                    son4m.put("准全款原因", "无");
                    son4m.put("准全款原因内容", null);
                }

            } else {
                son4m.put("准全款原因", "无");
                son4m.put("准全款原因内容", null);
            }
            if (lsh金融申请表.get战败原因() != null && !"".equals(lsh金融申请表.get战败原因())) {

                nolist1 = repository.getstatusbysqls(lsh金融申请表.get战败原因());///
                if (nolist1.size() > 0) {

                    son5m = (Map) nolist1.get(0);
                    if (son5m.get("d") != null) {
                        son4m.put("战败原因内容", son5m.get("d").toString());
                        son4m.put("战败原因", "有");
                    } else {
                        son4m.put("战败原因", "无");
                        son4m.put("战败原因内容", null);
                    }

                } else {
                    son4m.put("战败原因", "无");
                    son4m.put("战败原因内容", null);
                }

            } else {
                son4m.put("战败原因内容", null);
                son4m.put("战败原因", "无");
            }


            nolist3.add(son4m);
            result.setData(nolist3);
            flag += "true";
        } catch (Exception e) {
            logger.error("准战败 获取有错误", e);
            msg += "出错了";
            flag += "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;


    }

    private String zhuanhuan(String xman) {
        String result = "";
        if (xman.equals("01")) {
            result = "汽车金融未报价";
        } else if (xman.equals("02")) {
            result = "汽车金融报价完成";
        } else if (xman.equals("03")) {
            result = "汽车金融准战败";
        } else if (xman.equals("04")) {
            result = "汽车金融战败";
        } else if (xman.equals("05")) {
            result = "金融意向确认";
        } else if (xman.equals("06")) {
            result = "已申请-待批复";
        } else if (xman.equals("07")) {
            result = "已申请-批复通过";
        } else if (xman.equals("08")) {
            result = "已申请-批复未通过";
        } else if (xman.equals("09")) {
            result = "金融通过后撤单";
        } else if (xman.equals("10")) {
            result = "金融抵押完成";
        } else if (xman.equals("11")) {
            result = "金融放款到帐";
        } else if (xman.equals("12")) {
            result = "新车战败";
        } else if (xman.equals("13")) {
            result = "撤单后重申请";
        } else if (xman.equals("14")) {
            result = "条件批复";
        } else {
            result = "汽车金融未报价";
        }
        return result;
    }

    public ResultData getFinancialAnnualDetailSingleApprove(GetFinancePoundageListRequest re, String permit) {
        ResultData resl = new ResultData();

        String flag = "";
        String msg = "1";
        List nolist3 = new ArrayList<>();
        PageData result = new PageData(nolist3, nolist3.size());
        List nolist1 = new ArrayList<>();

        Map son4m = new HashMap();
        Map son5m = null;
        try {
            Lsh金融申请Model lsh金融申请表 = lsh金融申请表Repository.getApplyFinanceModelByIds(re.permissionCode);


            if (lsh金融申请表.get申请日期() != null && !"".equals(lsh金融申请表.get申请日期())) {
                if (lsh金融申请表.get申请结果日期() != null && !"".equals(lsh金融申请表.get申请结果日期())) {
                    son4m.put("申请结果", "通过");
                    son4m.put("申请结果日期", lsh金融申请表.get申请结果日期());
                    son4m.put("意向方案申请", "有");
                    son4m.put("意向日期", lsh金融申请表.get申请日期());
                } else {
                    son4m.put("意向方案申请", "有");
                    son4m.put("意向日期", lsh金融申请表.get申请日期());
                    son4m.put("申请结果", "未通过");
                    son4m.put("申请结果日期", null);
                }
            } else {
                son4m.put("意向方案申请", "无");
                son4m.put("意向日期", null);
                son4m.put("申请结果", "未通过");
                son4m.put("申请结果日期", null);
            }

            if (lsh金融申请表.get准全款原因() != null && !"".equals(lsh金融申请表.get准全款原因())) {

                nolist1 = repository.getstatusbysqls(lsh金融申请表.get准全款原因());///
                if (nolist1.size() > 0) {

                    son5m = (Map) nolist1.get(0);
                    if (son5m.get("d") != null) {
                        son4m.put("准全款原因内容", son5m.get("d").toString());
                        son4m.put("准全款原因", "有");
                    } else {
                        son4m.put("准全款原因", "无");
                        son4m.put("准全款原因内容", null);
                    }

                } else {
                    son4m.put("准全款原因", "无");
                    son4m.put("准全款原因内容", null);
                }

            } else {
                son4m.put("准全款原因", "无");
                son4m.put("准全款原因内容", null);
            }
            if (lsh金融申请表.get战败原因() != null && !"".equals(lsh金融申请表.get战败原因())) {

                nolist1 = repository.getstatusbysqls(lsh金融申请表.get战败原因());///
                if (nolist1.size() > 0) {

                    son5m = (Map) nolist1.get(0);
                    if (son5m.get("d") != null) {
                        son4m.put("战败原因内容", son5m.get("d").toString());
                        son4m.put("战败原因", "有");
                    } else {
                        son4m.put("战败原因", "无");
                        son4m.put("战败原因内容", null);
                    }

                } else {
                    son4m.put("战败原因", "无");
                    son4m.put("战败原因内容", null);
                }

            } else {
                son4m.put("战败原因内容", null);
                son4m.put("战败原因", "无");
            }


            son4m.put("金融销售状态", zhuanhuanqiantai(lsh金融申请表.get状态()));////

            nolist3.add(son4m);
            result.setData(nolist3);
            flag += "true";
        } catch (Exception e) {
            logger.error("战败原因 获取有错误", e);
            msg += "出错了";
            flag += "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;


    }


    public ResultData saveActivateFinancialFail(GetFinancePoundageListRequest re, String permit) {
        // 根据  初始报价编号 查出来先
        ResultData resl = new ResultData();

        String flag = "";
        String msg = "";
        List nolist3 = new ArrayList<>();
        PageData result = new PageData(nolist3, nolist3.size());
        List nolist1 = new ArrayList<>();

        Map son1m = new HashMap();

        try {
            Lsh金融申请Model lsh金融申请表 = lsh金融申请表Repository.getApplyFinanceModelByIds(re.permissionCode);
            FinanceLogModel savemodel = new FinanceLogModel();
            Timestamp date = new Timestamp(System.currentTimeMillis());
            savemodel.setLogTime(date);
            savemodel.setLogUser(permit);
            savemodel.setState(lsh金融申请表.get状态());
            savemodel.setOrgQsn(re.permissionCode);
            financeLogRepository.save(savemodel);
            msg += "保存到日志文件成功";
            flag += "true";

            //然后 就把 以前的 状态 全部清空
            lsh金融申请表.set状态("01");
            lsh金融申请表.set申请日期(null);
            lsh金融申请表.set战败原因(null);
            lsh金融申请表.set抵押日期(null);
            lsh金融申请表.set申请结果日期(null);
            lsh金融申请表.set更新账号(permit);
            lsh金融申请表.set更新时间(date);
            lsh金融申请表.set准全款备注(null);
            lsh金融申请表.set战败备注(null);
            lsh金融申请表Repository.save(lsh金融申请表);
            msg += "状态已经清空";
        } catch (Exception e) {
            logger.error("数据保存异常。", e);
            msg += "出错了";
            flag += "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;

    }

    public ResultData saveFinancialFailStatus(GetFinancePoundageListRequest re, String permit, String postman) {
        // 根据  初始报价编号 查出来先
        ResultData resl = new ResultData();

        String flag = "";
        String msg = "";
        List nolist3 = new ArrayList<>();
        PageData result = new PageData(nolist3, nolist3.size());
        List nolist1 = new ArrayList<>();

        Map son1m = new HashMap();

        try {
            Lsh金融申请Model lsh金融申请表 = lsh金融申请表Repository.getApplyFinanceModelByIds(re.permissionCode);
            FinanceLogModel savemodel = new FinanceLogModel();
            Timestamp date = new Timestamp(System.currentTimeMillis());
            savemodel.setLogTime(date);
            savemodel.setLogUser(permit);
            savemodel.setState("4");// 金融战败  日志文件
            savemodel.setOrgQsn(re.permissionCode);
            financeLogRepository.save(savemodel);
            msg += "保存到日志文件成功";
            flag += "true";

            //
            lsh金融申请表.set状态("04");
            lsh金融申请表.set申请日期(null);
            int reason = getfinancefailreason(re.reason, permit, postman);
            lsh金融申请表.set战败原因(reason);// 战败 原因 保存 前台传入的   如果 有，则是 直接取出编号
            // 如果没有  则是直接 保存的是    先插入 战败 原因表 和   战败原因附属 表  之后  生成的  编号
            lsh金融申请表.set抵押日期(null);
            lsh金融申请表.set申请结果日期(null);
            lsh金融申请表.set更新账号(postman);
            lsh金融申请表.set更新时间(date);
            lsh金融申请表.set申请日期(null);
            lsh金融申请表.set准全款备注(null);
            lsh金融申请表.set战败备注(null);
            lsh金融申请表Repository.save(lsh金融申请表);
            msg += "状态已经改成战败";
        } catch (Exception e) {
            logger.error("状态更改错误", e);
            msg += "出错了";
            flag += "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;

    }

    private int getfinancefailreason(String reson, String permit, String user) {
        int reasonid = 0;
        List<Lsh金融战败原因Model> sonnewosn = lsh金融战败原因Repository.getstatusbyreasonAndsql(reson);

        if (sonnewosn != null && sonnewosn.size() > 0) {
            reasonid = sonnewosn.get(0).get金融战败原因编号();
        } else {
            Lsh金融战败原因Model var1 = new Lsh金融战败原因Model();
            var1.set启用状态("启用");
            var1.set许可(permit);
            var1.set战败原因(reson);
            var1.set更新账号(user);
            Timestamp date = new Timestamp(System.currentTimeMillis());
            var1.set创建时间(date);
            var1.set是否输入("是");
            var1.set更新时间(date);
            Lsh金融战败原因Model modelvar = lsh金融战败原因Repository.save(var1);

            saveFinanceFailRely(modelvar);
            reasonid = modelvar.get金融战败原因编号();

        }
        return reasonid;
    }

    private int getfinancezhunfailreason(String reson, String permit, String user) {
        int reasonid = 0;
        try {
            List<Lsh金融战败原因Model> sonnewosn = lsh金融战败原因Repository.getstatusbyreasonAndsql(reson);
            if (sonnewosn != null && sonnewosn.size() > 0) {
                reasonid = sonnewosn.get(0).get金融战败原因编号();
            } else {

                Lsh金融战败原因Model var1 = new Lsh金融战败原因Model();
                var1.set启用状态("启用");
                var1.set许可(permit);
                var1.set战败原因(reson);
                var1.set更新账号(user);
                Timestamp date = new Timestamp(System.currentTimeMillis());
                var1.set创建时间(date);
                var1.set是否输入("是");
                var1.set更新时间(date);
                Lsh金融战败原因Model modelvar = lsh金融战败原因Repository.save(var1);

                saveFinanceFailRelys(modelvar);
                reasonid = modelvar.get金融战败原因编号();

            }
        } catch (Exception e) {
            logger.error("获取战败原因失败", e);

        }
        return reasonid;
    }

    private void saveFinanceFailRely(Lsh金融战败原因Model modelvar) {

        Lsh金融战败原因附属Model var = new Lsh金融战败原因附属Model();
      /*  var.set战败内容(modelvar.get战败原因());*/
        var.set战败分类("金融战败");
        var.set金融战败原因编号(modelvar.get金融战败原因编号());
        lsh金融战败原因附属Repository.save(var);
    }

    private void saveFinanceFailRelys(Lsh金融战败原因Model modelvar) {
        Lsh金融战败原因附属Model var = new Lsh金融战败原因附属Model();
     /*   var.set战败内容(modelvar.get战败原因());*/
        var.set战败分类("准全款");
        var.set金融战败原因编号(modelvar.get金融战败原因编号());
        lsh金融战败原因附属Repository.save(var);
    }


    public ResultData getLoanClientDetaiNoFail(GetFinancePoundageListRequest re, String permit) {
        ResultData resl = new ResultData();
        String flag = "";
        String msg = "";
        ArrayList nolist3 = new ArrayList();
        PageData result = new PageData(nolist3, nolist3.size());
        new ArrayList();
        HashMap james = new HashMap();

        try {
            Lsh金融申请Model e = this.lsh金融申请表Repository.getApplyFinanceModelByIds(re.permissionCode);
            if (!Strings.isNullOrEmpty(e.get状态())) {
                /////
                String shenpi = zhuanhuan(e.get状态());
                james.put("审批通过后状态跟踪", shenpi);
            }
            if (e.get申请结果日期() != null) {
                james.put("申请结果日期", e.get申请结果日期());
            } else {
                james.put("申请结果日期", "没有");
            }
            if (e.get撤单日期() != null && !"".equals(e.get撤单日期())) {
                james.put("撤单", "是");
                james.put("撤单日期", e.get撤单日期());
                james.put("撤单原因", e.get撤单原因());
            } else {
                james.put("撤单", "否");
                james.put("撤单日期", null);
                james.put("撤单原因", null);
            }

            if (e.get退款金额() != null && !"".equals(e.get退款金额())) {
                james.put("退款", "是");
                james.put("退款金额", e.get退款金额());
            } else {
                james.put("退款", "否");
                james.put("退款金额", "0");
            }

            if (e.get重新申请日期() != null && !"".equals(e.get重新申请日期())) {
                james.put("重新申请日期", "是");
                james.put("重新申请日期", e.get重新申请日期());
            } else {
                james.put("重新申请日期", "没有");
                james.put("重新申请日期", (Object) null);
            }

            if (e.get重新申请日期() != null && !"".equals(e.get重新申请日期())) {
                james.put("重新申请金融服务费", "有");
                james.put("重新申请金融服务费", e.get重新申请金融服务费());
            } else {
                james.put("重新申请金融服务费", "没有");
                james.put("重新申请金融服务费", (Object) null);
            }

            if (e.get抵押日期() != null && !"".equals(e.get抵押日期())) {
                james.put("抵押日期", "有");
                james.put("抵押日期", e.get抵押日期());
            } else {
                james.put("抵押日期", "没有");
                james.put("抵押日期", (Object) null);
            }

            if (e.get放款日期() != null && !"".equals(e.get放款日期())) {
                james.put("放款日期", "有");
                james.put("放款日期", e.get放款日期());
                String  periods  = this.repository.getLoanPeriods(permit,e.get初始报价单号());
                if(!Strings.isNullOrEmpty(periods)){
                    Date date = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(e.get放款日期());
                    cl.add(Calendar.MONTH,Integer.parseInt(periods));
                    cl.add(Calendar.DAY_OF_MONTH,-1);
                    date = cl.getTime();
                    james.put("贷款到期日",sdf.format(date));
                }else {
                    james.put("贷款到期日", null);
                }
            } else {
                james.put("放款日期", "没有");
                james.put("放款日期", (Object) null);
                james.put("贷款到期日",null);
            }

            nolist3.add(james);
            result.setTotal(nolist3.size());
            result.setData(nolist3);
            msg = msg + "查询出来了";
            flag = flag + "true";
        } catch (Exception e) {
            logger.error("获取错误", e);
            msg = msg + "出错了";
            flag = flag + "false";
        }

        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;
    }


    public ResultData saveLoanClientFinanceApproveStatus(getkobejamesandoneal oneal, String postman, String permit) {
        ResultData resl = new ResultData();
        String flag = "";
        String msg = "";
        ArrayList nolist3 = new ArrayList();
        PageData result = new PageData(nolist3, nolist3.size());
        new ArrayList();
        new HashMap();
        new SimpleDateFormat("yyyy-MM-ss");
        java.sql.Date cba = null;

        try {
            Lsh金融申请Model e = this.lsh金融申请表Repository.getApplyFinanceModelByIds(oneal.bill);
            Timestamp nowtime = new Timestamp(System.currentTimeMillis());
            e.set更新时间(nowtime);
            if (e != null) {
                if (e.get操作人() == null) {
                    //如果 以前的 操作人是 空
                    e.set操作人(postman);
                    e.set更新账号(postman);
                } else {
                    String starman = e.get操作人();
                    if (!starman.equals(postman)) {
                         /* 如果 两次操作的 人 不一样，那么 我需要 对 当前操作人 做记录
                           同时 需要 对 修改 的内容 做 记录
                         */
                        saveFinanceShenqingUpdateHositoryLog(e, postman, oneal.bill);
                    }
                }
            }

            if (!Strings.isNullOrEmpty(oneal.applyType)) {
                //  0 通过  1 不通过   2 条件批复
                if (oneal.applyType.equals("2")) {
                    e.set状态("14");
                    e.set申请结果日期(null);
                } else if (oneal.applyType.equals("0")) {
                    e.set状态("07");
                    e.set申请结果日期(null);
                    e.setApplyPassDate(new java.sql.Date(new java.util.Date().getTime()));  //
                } else {
                    e.set状态("08");
                    e.set申请结果日期(null);
                }
            }


            if (oneal.issoledate != null && !"".equals(oneal.issoledate)
                    && oneal.issolereason != null && !"".equals(oneal.issolereason)) {
                cba = java.sql.Date.valueOf(oneal.issoledate);
                e.set撤单日期(cba);
                // 直接 就是 把 金融状态 改成 金融战败  手续费 是否清零 还在 确认----确认清零
                Lsh金融申请Model cleanModel = lsh金融申请表Repository.getApplyFinanceModelByIds(oneal.bill);
                savefinanceLog(oneal.bill, "09", postman);
                /**
                 * 选择撤单后，销售顾问应进行订单/合同修改，将客户的报价单更新为全款客户，
                 * 选择金融状态为准全款，
                 * 进行订单/合同审批通过后，客户的状态自动变更为金融战败，
                 * 且自动选择战败原因为“客户撤单”
                 *
                 * */
                cleanModel.set状态("04");

//                SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
//                if (!Strings.isNullOrEmpty(oneal.applyDate)) {
//                    java.util.Date date3 = formatter2.parse(oneal.applyDate);
//                    java.sql.Date sqlDate3 = new java.sql.Date(date3.getTime());
//                    cleanModel.set申请结果日期(sqlDate3);
//                }

                cleanModel.set申请结果日期(null);
                cleanModel.set申请日期(null);
                cleanModel.set抵押日期(null);
                cleanModel.set更新时间(nowtime);
                cleanModel.set战败原因(2);// 客户撤单 是 写死的
                if (cleanModel != null) {
                    if (cleanModel.get操作人() == null) {
                        //如果 以前的 操作人是 空
                        cleanModel.set操作人(postman);
                        cleanModel.set更新账号(postman);

                    } else {
                        String starman = e.get操作人();

                        if (!starman.equals(postman)) {
                         /* 如果 两次操作的 人 不一样，那么 我需要 对 当前操作人 做记录
                           同时 需要 对 修改 的内容 做 记录
                         */
                            saveFinanceShenqingUpdateHositoryLog(cleanModel, postman, oneal.bill);
                        }
                    }
                }

                cleanModel.set撤单原因(oneal.issolereason);
                cleanModel.set更新账号(postman);
                lsh金融申请表Repository.save(cleanModel);
                ///a保存到 附属表  里面
                // saveshenqingfushu(oneal.bill,postman,permit);
                //----确认清零+ 更新 报价付款详细  审批后状态跟踪
                flag = updateServiceFeeFinance(oneal.bill, permit);
                savefinanceLog(oneal.bill, "04", postman);
            }

            if (StringUtils.isNullOrBlank(oneal.iscustomermoney) || "否".equals(oneal.iscustomer)) {
                //没填退款金额或者金融服务费退还客户选择为否
                e.set退款金额(null);
            } else {
                e.set退款金额(oneal.iscustomermoney);
                savefinanceLog(oneal.bill, "09", postman);
            }
            // 需要 把消息 保存到 消息表  发送到 财务界面  暂时不推到财务界面
            //saveMsgTosolePeople(oneal.bill,postman,permit,oneal.iscustomermoney);
            // 记录在 log日志表里面

            //}


            if (oneal.iscustomertwodate != null && !"".equals(oneal.iscustomertwodate)) {
                cba = java.sql.Date.valueOf(oneal.iscustomertwodate);
                e.set重新申请日期(cba);
                e.set撤单原因(null);
                e.set撤单日期(null);
                e.set退款金额(null);
                //4ge
                e.set准全款原因(null);
                e.set准全款备注(null);
                e.set战败原因(null);
                e.set战败备注(null);
            }

            if (oneal.iscustomermoneytwo != null && !"".equals(oneal.iscustomermoneytwo)) {
                e.set重新申请金融服务费(oneal.iscustomermoneytwo);
                e.set状态("13");
                e.set申请日期(null);
                e.set申请结果日期(null);
                //需要 把消息 保存到 消息表  发送到 财务界面 并且 需要 重新计算 手续费
                saveMsgTosolePeople(oneal.bill, postman, permit, oneal.iscustomermoney);
                // 记录在 log日志表里面
                savefinanceLog(oneal.bill, "13", postman);
            }

            if (oneal.sucessdate != null && !"".equals(oneal.sucessdate) && (oneal.sucessfunldate == null || "".equals(oneal.sucessfunldate))) {
                cba = java.sql.Date.valueOf(oneal.sucessdate);
                e.set抵押日期(cba);
                e.set状态("10");// 金融抵押完成
                e.set撤单原因(null);
                e.set撤单日期(null);
                e.set退款金额(null);
                e.set重新申请日期(null);
                e.set重新申请金融服务费(null);
                e.set放款日期(null);
                e.set准全款原因(null);
                e.set准全款备注(null);
                e.set战败原因(null);
                e.set战败备注(null);
                // 极光推送
                sendMsganditask(permit, oneal.bill, postman);
                // 记录在 log日志表里面
                savefinanceLog(oneal.bill, "10", postman);
                //
            }

            if (oneal.sucessfunldate != null && !"".equals(oneal.sucessfunldate)) {
                cba = java.sql.Date.valueOf(oneal.sucessfunldate);
                e.set放款日期(cba);//金融放款到帐
                cba = java.sql.Date.valueOf(oneal.sucessdate);
                e.set抵押日期(cba);
                e.set状态("11");
                e.set撤单原因(null);
                e.set撤单日期(null);
                e.set退款金额(null);
                e.set重新申请日期(null);
                e.set重新申请金融服务费(null);

                e.set准全款原因(null);
                e.set准全款备注(null);
                e.set战败原因(null);
                e.set战败备注(null);
                // 极光推送
                sendMsganditask(permit, oneal.bill, postman);
                // 记录在 log日志表里面
                savefinanceLog(oneal.bill, "11", postman);
            }
            if (!Strings.isNullOrEmpty(oneal.applyDate)) {
                SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
                Date date3 = formatter2.parse(oneal.applyDate);
                java.sql.Date sqlDate3 = new java.sql.Date(date3.getTime());
                e.set申请结果日期(sqlDate3);
            }
            Lsh金融申请Model models = this.lsh金融申请表Repository.save(e);
            nolist3.add(models);
            updateApprovalModel(models.get状态(),oneal,postman);

            msg = msg + "保存信息成功";
            flag = flag + "true";
        } catch (Exception var14) {
            logger.error("审批后跟踪状态出错", var14);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            msg = msg + "出错了";
            flag = flag + "false";
        }
        result.setData(nolist3);
        resl.setMessage(msg);
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;
    }


    private void updateApprovalModel(String fianceStatus,getkobejamesandoneal oneal,String postman){
        String status= zhuanhuan(fianceStatus);
        List<ApproveHistoryLogModel> judgeInitQueto = approveHistoryLogRepository.findStarIds(oneal.bill);
        // 根据报价单号---》查到金融机构
        报价单表Model 报价单表Modelmodel =  报价单表Repository.findBy初始报价编号(oneal.bill).get(0);
        String orgs="";
        if(报价单表Modelmodel.get金融()!=null){
            报价金融表Model models = 报价金融表Repository.getLatestfinalMsgs(报价单表Modelmodel.get金融());
            if (models.get金融机构()!=null){
                orgs=models.get金融机构();
            }
        }

        if(judgeInitQueto!=null&&judgeInitQueto.size()>0){
            List<ApproveHistoryLogModel> judgeInitQuetoAndOrgs=approveHistoryLogRepository.findStarIdsAndOrgs(oneal.bill,orgs);
            if(judgeInitQuetoAndOrgs!=null&&judgeInitQuetoAndOrgs.size()>0){
                //以前就有，那么就是更新
                ApproveHistoryLogModel updateModel=judgeInitQuetoAndOrgs.get(0);
                updateModel.set审批状态(status);
                updateModel.set申请日期(new Timestamp(System.currentTimeMillis()));
                updateModel.set更新日期(new Timestamp(System.currentTimeMillis()));
                approveHistoryLogRepository.save(updateModel);
            } else{
                // 之前没有，就直接插入
                ApproveHistoryLogModel insertModel = new ApproveHistoryLogModel();
                insertModel.set初始报价单号(oneal.bill);
                insertModel.set金融机构(orgs);
                insertModel.set审批状态(status);
                insertModel.set更新账号(postman);
                insertModel.set申请日期(new Timestamp(System.currentTimeMillis()));
                insertModel.set更新日期(new Timestamp(System.currentTimeMillis()));
                approveHistoryLogRepository.save(insertModel);
            }
        }else{
            // 之前没有，就直接插入
            ApproveHistoryLogModel insertModel = new ApproveHistoryLogModel();
            insertModel.set初始报价单号(oneal.bill);
            insertModel.set金融机构(orgs);
            insertModel.set审批状态(status);
            insertModel.set更新账号(postman);
            insertModel.set申请日期(new Timestamp(System.currentTimeMillis()));
            insertModel.set更新日期(new Timestamp(System.currentTimeMillis()));
            approveHistoryLogRepository.save(insertModel);
        }
        return;
    }

    private String updateServiceFeeFinance(String bill, String permit) {
        String flag = "";
        /**
         *   根据初始报价编号   20010101010  拿到所有的 金融不为空 的   排倒叙
         *      第一个 出现 ”  是 “ 的 48--43 全部清空；
         * **/
//        List areaList = repository.findAllFinanceFee(bill);

        try {
//            if (areaList != null && areaList.size() > 0) {
//                for (int i = 0; i < areaList.size(); i++) {
//                    Map nimao = (Map) areaList.get(i);
//                    String duncan = nimao.get("金融").toString();
//                    if (duncan != null) {
//                        报价金融表Model tim = 报价金融表Repository.findOne(Integer.parseInt(duncan));
//                        if (tim != null) {
//                            tim.set金融手续费(null);
//                            tim.set金融集团手续费(null);
//                        }
//                        报价金融表Repository.save(tim);
//                    }
//                }
//            }

            // 需要 把  报价 单表 + 报价付款详细 的 总计 金融首付 尾款  都进行 更改
            // 拿到的 是 最大的 报价编号且 还原点是  是 的数据
            List MaxRestore = repository.findIsRestoreAndLoanDetail(bill);
            Map restoreMap = new HashMap();
            if (MaxRestore != null && MaxRestore.size() > 0) {
                restoreMap = (Map) MaxRestore.get(0);
                String LoanDetailid = restoreMap.get("id").toString();
                updateFianceFee(LoanDetailid, permit);
            }


            flag = "true";
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.warn(String.format("清空手续费出错。初始报价单号=%s, " +
                    "许可=%s ", bill, permit));
            flag = "false";
        }
        return flag;

    }

    private String updateFianceFee(String yuanshi, String permit) {
        String flag = "false";
        try {
            // 根据  id报价编号  把 金融服务费拿出来 在报价金融表
            报价单表Model yuanshimodel = 报价单表Repository.findBy报价编号(Integer.parseInt(yuanshi));
            String LoanDetailid = null;
            if (yuanshimodel != null) {
                if (yuanshimodel.get金融() != null) {
                    LoanDetailid = String.valueOf(yuanshimodel.get金融());
                }


                报价金融表Model items = 报价金融表Repository.findOne(Integer.parseInt(LoanDetailid));
                double fee = 0d;
                if (items != null) {
                    if (items.get金融服务费() != null && !"".equals(items.get金融服务费())) {
                        fee = Double.parseDouble(items.get金融服务费());
                    } else {
                        fee = 0d;
                    }

                }
                // 金融服务费的 填入
                报价付款详细ModelPK itemfeepk = new 报价付款详细ModelPK();
                itemfeepk.set报价编号(Integer.parseInt(yuanshi));
                itemfeepk.set付款事由("金融服务费");
                double yuanyoufee = 0d;

                报价付款详细Model onemodel = 报价付款详细repository.findOne(itemfeepk);
                if (onemodel == null) {
                    // 如果 说 以前 没有这个 列  那么就需要 重新 新插入
                    报价付款详细Model newonemodel = new 报价付款详细Model();
                    newonemodel.set付款事由("金融服务费");
                    newonemodel.set报价编号(Integer.parseInt(yuanshi));
                    newonemodel.set应付金额(Double.toString(fee));
                    newonemodel.set更新账号(permit);
                    newonemodel.set更新时间(new Timestamp(System.currentTimeMillis()));
                    报价付款详细repository.save(newonemodel);
                    // 总计 修改
                    报价付款详细ModelPK sumPriceModelpks = new 报价付款详细ModelPK();
                    sumPriceModelpks.set报价编号(Integer.parseInt(yuanshi));
                    sumPriceModelpks.set付款事由("总计");
                    报价付款详细Model sumPriceModels = 报价付款详细repository.findOne(sumPriceModelpks);
                    if (sumPriceModels != null) {
                        double sumszongji = Double.parseDouble(sumPriceModels.get应付金额());
                        sumszongji += fee;
                        sumPriceModels.set应付金额(Double.toString(sumszongji));
                        报价付款详细repository.save(sumPriceModels);
                    } else {
                        flag = "false";
                    }

                } else {
                    yuanyoufee = Double.parseDouble(onemodel.get应付金额());

                    onemodel.set应付金额(String.valueOf(fee));
                    onemodel.set更新账号(permit);
                    onemodel.set更新时间(new Timestamp(System.currentTimeMillis()));
                    报价付款详细repository.save(onemodel);

                    // 总计 修改
                    报价付款详细ModelPK sumPriceModelpks = new 报价付款详细ModelPK();
                    sumPriceModelpks.set报价编号(Integer.parseInt(yuanshi));
                    sumPriceModelpks.set付款事由("总计");
                    报价付款详细Model sumPriceModels = 报价付款详细repository.findOne(sumPriceModelpks);
                    if (sumPriceModels != null) {
                        double sumszongji = Double.parseDouble(sumPriceModels.get应付金额());
                        sumszongji += (fee - yuanyoufee);
                        sumPriceModels.set应付金额(Double.toString(sumszongji));
                        sumPriceModels.set更新时间(new Timestamp(System.currentTimeMillis()));
                        sumPriceModels.set更新账号(permit);
                        报价付款详细repository.save(sumPriceModels);
                    } else {
                        flag = "false";
                    }


                }


            }
            flag = "true";
        } catch (Exception e) {
            logger.error("修改付款详细的 金融服务费 出错", e);
        }
        return flag;
    }

    private void sendMsganditask(String permit, String bill, String postman) {
        Map<String, String> map3 = this.repository.getClientInfoAndMsgBypermit(permit, bill);///
        String sc = map3.get("销售顾问");
        String cus = map3.get("顾客姓名");
        String sex = map3.get("称谓");
        String cell = map3.get("电话号码");
        Date shijian3 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 ");
        String shijiande = sdf.format(shijian3);
        String msg_content = "客户" + cus + sex + "，电话号码" + cell + "，新车金融抵押于  " + shijiande + "  已完成";
        LshMsgUtils.getLshMsg(permit, postman, null, sc, "金融", msg_content, postman, cell, "金融");
        List recList3 = new ArrayList();
        recList3.add(sc);
        JPush.sendPushForAndroidAndIos(msg_content, msg_content, null, recList3, JPush.Platforms.iTask);
    }

    private void sendMsganditaskshenpi(String permit, String bill, String postman) {
        Map<String, String> map3 = this.repository.getClientInfoAndMsgBypermit(permit, bill);///
        String sc = map3.get("销售顾问");
        String cus = map3.get("顾客姓名");
        String sex = map3.get("称谓");
        String cell = map3.get("电话号码");
        Date shijian3 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 ");
        String shijiande = sdf.format(shijian3);
        String msg_content = "客户" + cus + sex + "，电话号码" + cell + "，意向方案已提交，如需修改请联系金融专员" + shijiande + "   ";
        LshMsgUtils.getLshMsg(permit, postman, null, sc, "金融", msg_content, postman, cell, "金融");
        List recList3 = new ArrayList();
        recList3.add(sc);
        JPush.sendPushForAndroidAndIos(msg_content, msg_content, null, recList3, JPush.Platforms.iTask);
    }

    private void sendMsganditaskshenpiResultsucess(String permit, String bill, String postman) {

        Map<String, String> map3 = this.repository.getClientInfoAndMsgBypermit(permit, bill);///
        String sc = map3.get("销售顾问");
        String cus = map3.get("顾客姓名");
        String sex = map3.get("称谓");
        String cell = map3.get("电话号码");

        Date shijian3 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 ");
        String shijiande = sdf.format(shijian3);
        String msg_content = "客户" + cus + sex + "，电话号码" + cell + "，意向方案申请申请结果通过  " + shijiande + "   ";
        LshMsgUtils.getLshMsg(permit, postman, null, sc, "金融", msg_content, postman, cell, "金融");
        List recList3 = new ArrayList();
        recList3.add(sc);
        JPush.sendPushForAndroidAndIos(msg_content, msg_content, null, recList3, JPush.Platforms.iTask);
    }


    private void sendMsganditaskshenpiResultfail(String permit, String bill, String postman) {

        Map<String, String> map3 = this.repository.getClientInfoAndMsgBypermit(permit, bill);///
        String sc = map3.get("销售顾问");
        String cus = map3.get("顾客姓名");
        String sex = map3.get("称谓");
        String cell = map3.get("电话号码");
        Date shijian3 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 ");
        String shijiande = sdf.format(shijian3);
        String msg_content = "客户" + cus + sex + "，电话号码" + cell + "，意向方案申请结果 没有通过  " + shijiande + "   ";
        LshMsgUtils.getLshMsg(permit, postman, null, sc, "金融", msg_content, postman, cell, "金融");
        List recList3 = new ArrayList();
        recList3.add(sc);
        JPush.sendPushForAndroidAndIos(msg_content, msg_content, null, recList3, JPush.Platforms.iTask);
    }

    private void sendMsganditaskshenpifail(String permit, String bill, String postman) {
        try {
            Map<String, String> map3 = this.repository.getClientInfoAndMsgBypermit(permit, bill);///
            String sc = map3.get("销售顾问");
            String cus = map3.get("顾客姓名");
            String sex = map3.get("称谓");
            String cell = map3.get("电话号码");

            Date shijian3 = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 ");
            String shijiande = sdf.format(shijian3);
            String msg_content = "客户" + cus + sex + "，电话号码" + cell + "，意向方案 未申请   " + shijiande + "   ";
            LshMsgUtils.getLshMsg(permit, postman, null, sc, "金融", msg_content, postman, cell, "金融");
            List recList3 = new ArrayList();
            recList3.add(sc);
            JPush.sendPushForAndroidAndIos(msg_content, msg_content, null, recList3, JPush.Platforms.iTask);
        } catch (Exception e) {
            logger.error("发送信息失败", e);
        }
    }

    private void sendMsganditaskshenpizhanbai(String permit, String bill, String postman) {
        try {
            Map<String, String> map3 = this.repository.getClientInfoAndMsgBypermit(permit, bill);///
            String sc = map3.get("销售顾问");
            String cus = map3.get("顾客姓名");
            String sex = map3.get("称谓");
            String cell = map3.get("电话号码");

            Date shijian3 = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 ");
            String shijiande = sdf.format(shijian3);
            String msg_content = "客户" + cus + sex + "，电话号码" + cell + ", 金融战败  " + shijiande + "   ";
            LshMsgUtils.getLshMsg(permit, postman, null, sc, "金融", msg_content, postman, cell, "金融");
            List recList3 = new ArrayList();
            recList3.add(sc);
            JPush.sendPushForAndroidAndIos(msg_content, msg_content, null, recList3, JPush.Platforms.iTask);

        } catch (Exception e) {
            logger.error("发送信息失败", e);
        }
    }

    private void saveMsgTosolePeople(String bill, String postman, String permit, String iscustomermoney) {
        try {
            Map<String, String> map = this.repository.getClientInfoAndMsgBypermit(permit, bill);
            Map<String, String> map2 = this.repository.getClientInfoAndMsgBypermit(permit, bill);
            String sc = map.get("人员姓名");
            String cus = map.get("顾客姓名");
            String sex = map.get("称谓");
            String cell = map.get("电话号码");
            String jishou = map2.get("人员姓名");
            String msg_content = "退款给客户：" + cus + sex +
                    "，电话号码" + cell + "退款金额：" + iscustomermoney + " ,作为记录退款的凭证";
            LshMsgUtils.getLshMsg(permit, postman, null, jishou, "金融", msg_content, postman, cell, "金融");
        } catch (Exception e) {
            logger.error("发送信息失败", e);
        }
    }

    private void savefinanceLog(String bill, String sums, String postman) {
        try {
            FinanceLogModel newmodelone1 = new FinanceLogModel();
            newmodelone1.setOrgQsn(bill);
            newmodelone1.setState(sums);//2.7.3.1通过后撤单  需要 在 log 日志 添加 类型
                /*    00金融编辑中		=SC未提交计算申请
                    01金融未报价		=待报价
                    02金融报价完成		=报价完成
                    03金融准战败		=战败
                    04金融战败（app不可编辑，等待PC激活）
                    05金融意向确认
                    06金融已申请待批复
                    07金融已申请批复通过
                    08金融已申请批复未通过
                    09金融通过后撤单
                    10金融抵押完成
                    11金融放款到帐
                    12新车战败   13撤单后重新申请  */
            newmodelone1.setLogUser(postman);
            Timestamp nowtime1 = new Timestamp(System.currentTimeMillis());
            newmodelone1.setLogTime(nowtime1);

            financeLogRepository.save(newmodelone1);
        } catch (Exception e) {
            logger.error("发送信息失败", e);
        }
    }


    public ResultData getFinancialAnnualSingleApproveDetail(GetFinancePoundageListRequest re, String permit) {
        ResultData resl = new ResultData();
        String flag = "";
        String msg = "1";
        List reasonList = new ArrayList<>();
        PageData result = new PageData(reasonList, reasonList.size());
        List nolist1 = new ArrayList<>();

        Map james = new HashMap();
        Map james2 = new HashMap();
        StringBuilder ss = new StringBuilder("");
        try {
            reasonList = repository.getFailReasonList(re.permissionCode, permit);
            for (int i = 0; i < reasonList.size(); i++) {

                james = (Map) reasonList.get(i);
                if (reasonList.size() == 1) {
                    ss.append(james.get("战败原因").toString());
                } else if (i == reasonList.size() - 1) {
                    ss.append(james.get("战败原因").toString());
                } else {
                    ss.append(james.get("战败原因").toString() + ",");
                }
            }
            msg += "查询出来了";
            flag += "true";
            result.setData(reasonList);
            result.setTotal(reasonList.size());
        } catch (Exception e) {
            logger.error("获取战败原因出错", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            msg += "出错了";
            flag += "false";
        }

        resl.setMessage(ss.toString());
        resl.setPageData(result);
        resl.setResult(flag);
        return resl;


    }


    public ResultData findFinanceServeFreeGuidance(String permit) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            List list = new ArrayList<>();
            for (int i = 0; i < 12; i++) {
                List<?> listOne = repository.findFinanceServeFreeGuidance(permit, year, i + 1);
                if (listOne == null || listOne.size() < 1) {
                    Map map = new HashMap();
                    map.put("year", year);
                    map.put("集团指导值", 0);
                    map.put("经销商指导值", 0);
                    map.put("经销商实际值", 0);
                    list.add(map);
                } else {
                    //add by 黄永平 2017-06-23
                    //返回的经销商实际值，如果是空,统一为"0"
                    Map map = (Map) listOne.get(0);
                    if (map.get("经销商实际值") == null || "".equals(map.get("经销商实际值")) ||
                            "null".equalsIgnoreCase((String) map.get("经销商实际值"))) {
                        map.put("经销商实际值", "0");
                    }
                    list.add(map);
                }
            }
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 0));
        } catch (Exception e) {
            logger.error("查询金融服务费比例指导", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    public ResultData saveFinanceServeFreeGuidance(String permit, String username, GetFinanceServeFreeGuidance getFinanceServeFreeGuidance) {
        ResultData resultData = new ResultData("false", null, null);
        if (getFinanceServeFreeGuidance == null) {
            resultData.setMessage("经销商指导值不存在");
        }
        try {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            List<?> listStatrt = repository.findFinanceServeFreeGuidance(permit, year, Integer.parseInt(getFinanceServeFreeGuidance.month));
            if (listStatrt != null && listStatrt.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                java.sql.Date date = null;
                if (Integer.parseInt(getFinanceServeFreeGuidance.month) < 10) {
                    date = new java.sql.Date(sdf.parse(year + "0" + getFinanceServeFreeGuidance.month + "01").getTime());
                } else {
                    date = new java.sql.Date(sdf.parse(year + getFinanceServeFreeGuidance.month + "01").getTime());
                }
                lsh金融服务费Repository.updateFinanceServeFreeGuidance(permit, username, date, getFinanceServeFreeGuidance.num);
                resultData.setResult("true");
            } else {
                resultData.setMessage("集团未设置金融服务费指导");
            }
        } catch (Exception e) {
            logger.error("保存或插入经销商指导值异常", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
        return resultData;
    }

    @Override
    public ResultData getRevokeInfo(String permit) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List list = Lists.newArrayList();
            list = repository.getRevokeInfo(permit);
            resultData.setResult("true");
            resultData.setMessage("成功");
            resultData.setPageData(new PageData(list, 0));
        } catch (Exception e) {
            resultData.setMessage("获取失败");
            logger.error("撤单信息获取失败", e);
        }
        return resultData;
    }

    @Override
    public ResultData getRevokeLastUpdateInfo(String permit) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List list = Lists.newArrayList();
            list = repository.getRevokeLastUpdateInfo(permit);
            resultData.setResult("true");
            resultData.setMessage("成功");
            resultData.setPageData(new PageData(list, 0));
        } catch (Exception e) {
            resultData.setMessage("获取失败");
            logger.error("撤单信息获取失败", e);
        }
        return resultData;
    }

    @Override
    public ResultData saveRevokeInfo(String permit, String userName, RevokeInfo revokeInfo) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            if (revokeInfo.id != null && !"".equals(revokeInfo.id)) {
                FinanceCancelReasonModel model = financeCancelReasonRepository.findOne(revokeInfo.id);

                if (revokeInfo.reason != null && !"".equals(revokeInfo.reason)) {
                    model.setCancelReason(revokeInfo.reason);
                }
                if (revokeInfo.state != null && !"".equals(revokeInfo.state)) {
                    model.setState(revokeInfo.state);
                }
                model.setPermit(permit);
                model.setUpdateTime(new Timestamp(new Date().getTime()));
                model.setUpdateUser(userName);
                financeCancelReasonRepository.save(model);
                resultData.setMessage("修改成功");
                resultData.setResult("true");
            } else {
                FinanceCancelReasonModel model = new FinanceCancelReasonModel();
                List list = financeCancelReasonRepository.findfinanceCancelReasonModel(revokeInfo.reason);

                if (list != null && list.size() > 0) {
                    resultData.setMessage("保存失败，该原因已经存在");
                } else {
                    if (revokeInfo.reason != null && !"".equals(revokeInfo.reason)) {
                        model.setCancelReason(revokeInfo.reason);
                    }
                    if (revokeInfo.state != null && !"".equals(revokeInfo.state)) {
                        model.setState(revokeInfo.state);
                    }
                    model.setPermit(permit);
                    model.setCreateTime(new Timestamp(new Date().getTime()));
                    model.setUpdateTime(new Timestamp(new Date().getTime()));
                    model.setUpdateUser(userName);
                    financeCancelReasonRepository.save(model);
                    resultData.setMessage("保存成功");
                    resultData.setResult("true");
                }

            }
        } catch (Exception e) {
            resultData.setMessage("系统错误保存失败");
            logger.error("撤单原因保存失败", e);
        }
        return resultData;
    }

    public ResultData getScAndFcChatlog(String permit, String userName, getfinancialFailAllListitemtwothreeforss revokeInfo) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List resultList = new ArrayList();
            // 所有的 log 表 都会 加上一个 初始报价单号
            resultList = repository.getScAndFcChatlog(revokeInfo);
            if (resultList != null && resultList.size() > 0) {
                resultData.setMessage("历史备注如下");
            } else {
                resultData.setMessage("暂时没有历史备注");
            }
            PageData pg = new PageData();
            pg.setData(resultList);
            pg.setTotal(resultList.size());
            resultData.setPageData(pg);
            resultData.setResult("true");

        } catch (Exception e) {
            resultData.setMessage("金融获取聊天信息失败");
            logger.error("金融获取聊天信息失败", e);
            resultData.setResult("false");
        }
        return resultData;
    }


    public ResultData getLoanPageOffer(String permit, String userName, getfinancialFailAllListitemtwothreeforss revokeInfo) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List resultList = new ArrayList();
            PageData pg = new PageData();
            // 根据 报价编号 获取出 贷款客户的 报价方案
            resultList = repository.getLoanPageOffer(permit, revokeInfo);
            if (resultList != null && resultList.size() > 0) {
                pg.setData(resultList);
                pg.setTotal(resultList.size());
                resultData.setPageData(pg);

                resultData.setResult("true");
                resultData.setMessage("有数据");
            } else {
                resultData.setResult("false");
                resultData.setMessage("没有数据");
            }


        } catch (Exception e) {
            resultData.setMessage("获取贷款客户的报价申请信息失败");
            logger.error("获取贷款客户的报价申请信息失败", e);
        }
        return resultData;
    }

    public ResultData getLoanApproveLog(String permit, String userName, getfinancialFailAllListitemtwothreeforss revokeInfo) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List resultList = new ArrayList();
            PageData pg = new PageData();
            //
            resultList = repository.getLoanApproveLog(permit, revokeInfo);
            if (resultList != null && resultList.size() > 0) {
                pg.setData(resultList);
                pg.setTotal(resultList.size());
                resultData.setPageData(pg);

                resultData.setResult("true");
                resultData.setMessage("有数据");
            } else {
                resultData.setResult("false");
                resultData.setMessage("没有数据");
            }


        } catch (Exception e) {
            resultData.setMessage("获取贷款审批历史失败");
            logger.error("获取贷款审批历史失败", e);
        }
        return resultData;
    }

    @Override
    @Transactional
    public ResultData saveApproveHisitoryAndFianceOrganize(String permit, String userName, getfinancialFailAllListitemtwothreeforss re) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List resultList = new ArrayList();
            PageData pg = new PageData();
            Timestamp nowtime = new Timestamp(System.currentTimeMillis());
            // 初始报价编号+ 更新账号 + 申请 日期  + 金融机构  +审批 状态  + 更新日期
            //  re.chushibaojiabianhao+   + re.finaceorgs+  re.shenqingjieguo
            ApproveHistoryLogModel sourceModle=new ApproveHistoryLogModel();
            List<ApproveHistoryLogModel> judgeList=new ArrayList();
            List<ApproveHistoryLogModel> judgeTwoList=new ArrayList();
            judgeList= approveHistoryLogRepository.findStarIds(re.chushibaojiabianhao);
            //根据初始报价单号查到审批状态
            Lsh金融申请Model omodel=   lsh金融申请表Repository.getApplyFinanceModelByIds(re.chushibaojiabianhao);

            if(judgeList!=null&&judgeList.size()>0){
                judgeTwoList=approveHistoryLogRepository.findStarIdsAndOrgs(re.chushibaojiabianhao,re.finaceorgs);
                if(judgeTwoList!=null&&judgeTwoList.size()>0){
                    //以前就有，那么就只是把更新时间和审批状态更新一下
                    ApproveHistoryLogModel updateModel=judgeTwoList.get(0);
                    updateModel.set申请日期(nowtime);
                    updateModel.set更新日期(nowtime);
                    if(omodel!=null){
                        updateModel.set审批状态(zhuanhuan(omodel.get状态()));
                    }
                    approveHistoryLogRepository.save(updateModel);
                }else{
                    insertApprovalHisitoryModel(permit,userName,nowtime,re,zhuanhuan(omodel.get状态()));
                }
            }else{
                // 以前没有申请过，直接就insert
                insertApprovalHisitoryModel(permit,userName,nowtime,re,zhuanhuan(omodel.get状态()));
            }

            resultData.setMessage("保存 贷款审批历史成功");
            resultData.setResult("true");

        } catch (Exception e) {
            resultData.setMessage("保存 贷款审批历史失败");
            resultData.setResult("false");
            logger.error("保存贷款审批历史失败", e);
        }
        return resultData;
    }

    private void insertApprovalHisitoryModel(String permit, String userName,
                                             Timestamp nowtime,
                                             getfinancialFailAllListitemtwothreeforss re,String status) {
        ApproveHistoryLogModel insertModel=new ApproveHistoryLogModel();
        if(!Strings.isNullOrEmpty(re.chushibaojiabianhao)){
            insertModel.set初始报价单号(re.chushibaojiabianhao);
        }
        if(!Strings.isNullOrEmpty(re.finaceorgs)){
            insertModel.set金融机构(re.finaceorgs);
        }
        insertModel.set审批状态(status);
        insertModel.set申请日期(nowtime);
        insertModel.set更新日期(nowtime);
        insertModel.set更新账号(userName);
        approveHistoryLogRepository.save(insertModel);

    }


    public ResultData getAllRateByFinanceType(getFinanceItem item, String permit, String userName) {
        ResultData rd = new ResultData();
        PageData pg = new PageData();
        List relist = new ArrayList();
        if (!Strings.isNullOrEmpty(item.finannceOrg)) {
            String trueType = "利率";
            if (!Strings.isNullOrEmpty(item.type)) {
                if (item.type.equals("1")) {
                    trueType = "费率";
                }
            }
            relist = repository.findAllRateListByorgs(item.finannceOrg, trueType, permit);
        }

        pg.setData(relist);
        rd.setPageData(pg);
        return rd;
    }

    public ResultData getFinanceOrgsAndYearRateList(String permit, String postman, getCounter re) {
        ResultData rd = new ResultData();
        PageData pg = new PageData();
        String flag = "true";
        String msg = "查询成功";
        List relist = new ArrayList();
        // 根据 车型编号 查询出
        Lsh车型Model onmodel = lsh车型Repository.findOne(Integer.parseInt(re.carprice));
        String source = onmodel.get来源();
        String brand = onmodel.get品牌();
        String jibie = onmodel.get级别();
        String carmodel = onmodel.get车型();
        String carmodelDetail = onmodel.get车型详细();
        List<String> listStr = new ArrayList<>();
        listStr.add(source);
        listStr.add(brand);
        listStr.add(jibie);
        listStr.add(carmodel);
        listStr.add(carmodelDetail);
        relist = this.repository.getFinanceOrgsAndYearRateList(permit, postman, re, listStr);
        pg.setData(relist);
        rd.setResult(flag);
        rd.setPageData(pg);
        return rd;
    }

    public ResultData getIsBelongToOrgs(String permit, String postman, getCounter re) {
        ResultData rd = new ResultData();
        PageData pg = new PageData();
        String flag = "true";
        String msg = "查询成功";
        List relist = new ArrayList();
        // 根据 车型编号 查询出
        Lsh车型Model onmodel = lsh车型Repository.findOne(Integer.parseInt(re.carprice));
        String source = onmodel.get来源();
        String brand = onmodel.get品牌();
        String jibie = onmodel.get级别();
        String carmodel = onmodel.get车型();
        String carmodelDetail = onmodel.get车型详细();
        List<String> listStr = new ArrayList<>();
        listStr.add(source);
        listStr.add(brand);
        listStr.add(jibie);
        listStr.add(carmodel);
        listStr.add(carmodelDetail);
        boolean resultflag = true;
        resultflag = this.repository.getIsBelongToOrgs(permit, postman, re, listStr);
        if (resultflag) {
            rd.setResult("true");
            rd.setMessage("有数据");
        } else {
            rd.setResult("false");
            rd.setMessage("没有数据");
        }
        rd.setPageData(pg);
        return rd;
    }

    @Override
    public List<QuoteFinanceInfo> getFinanceSettings(String dlcode, String carId, String companyId, String yearRate,
                                                     String loanterm, String downRate, String balRate, String loanAmount, String type) {
        List<QuoteFinanceInfo> resultList = new ArrayList<>();
        try {
            QuoteFinanceInfo quoteFinanceInfo = new QuoteFinanceInfo();
            quoteFinanceInfo.setType(type);
            Lsh车型Model lsh车型Model = null;
            //校验车型编号
            if (carId == null || "".equals(carId)) {
                quoteFinanceInfo.setMessage("车型编号不能为空或者为null");
                resultList.add(quoteFinanceInfo);
                return resultList;
            }
            lsh车型Model = lsh车型Repository.findOne(Integer.parseInt(carId));
            //校验根据车型编号查出的信息
            if (lsh车型Model == null) {
                quoteFinanceInfo.setMessage("未找到相关车型信息");
                resultList.add(quoteFinanceInfo);
                return resultList;
            }
            //筛选满足条件的金融信息
            List list = repository.getFinanceSettings(dlcode, carId, lsh车型Model.get来源(), lsh车型Model.get品牌(),
                    lsh车型Model.get级别(), lsh车型Model.get车型(), lsh车型Model.get车型详细(), companyId, yearRate,
                    loanterm, downRate, balRate, type);
            //判断是否有满足条件的金融信息
            if (list != null && !list.isEmpty()) {
                //  type = 1 获取金融机构列表
                //  type = 2 获取金融期数列表
                //  type = 3 获取金融年利率列表
                //  type = 4 获取金融最低首付比例
                //  type = 5 获取金融最高尾款比例
                if ("1".equals(type)) {
                    ArrayList<String> listCompany = new ArrayList();
                    ArrayList<String> listCompanyId = new ArrayList();
                    for (Object o : list) {
                        Map map = (Map) o;
                        listCompany.add(map.get("金融机构") == null ? null : map.get("金融机构").toString());
                        listCompanyId.add(map.get("金融机构编号") == null ? null : map.get("金融机构编号").toString());
                    }
                    quoteFinanceInfo.setFinanceBankNameAry(listCompany);
                    quoteFinanceInfo.setFinanceBankIDAry(listCompanyId);
                } else if ("2".equals(type)) {
                    ArrayList<String> listLoanterm = new ArrayList();
                    for (Object o : list) {
                        Map map = (Map) o;
                        listLoanterm.add(map.get("期数") == null ? null : map.get("期数").toString());
                    }
                    quoteFinanceInfo.setFinanceLoanTerm(listLoanterm);
                } else if ("3".equals(type)) {
                    ArrayList<String> listYearRate = new ArrayList();
                    String yearRateState = "";
                    for (int i = 0; i < list.size(); i++) {
                        Map map = (Map) list.get(i);
                        listYearRate.add(map.get("年利率") == null ? null : map.get("年利率").toString());
                        if (i > 0) {
                            yearRateState = yearRateState + "___MARK___";
                        }
                        yearRateState = yearRateState + (map.get("利率状态") == null ? "" : map.get("利率状态").toString());
                    }
                    quoteFinanceInfo.setFinanceYearlyRateAry(listYearRate);
                    quoteFinanceInfo.setFinanceYearlyRateStyle(yearRateState);
                } else if ("4".equals(type)) {
                    String financeDownPaymentRate = ((Map) list.get(0)).get("最低首付比例") == null ? null : ((Map) list.get(0)).get("最低首付比例").toString();
                    quoteFinanceInfo.setFinanceDownPaymentRate(financeDownPaymentRate);
                } else if ("5".equals(type)) {
                    String financeBalanceRate = ((Map) list.get(0)).get("最高尾款比例") == null ? null : ((Map) list.get(0)).get("最高尾款比例").toString();
                    quoteFinanceInfo.setFinanceBalanceRate(financeBalanceRate);
                }
                //根据条件查询 金融方案 是否唯一，如果 唯一，将金融方案其他信息返回
                List listInfo = repository.getFinanceSettingsInfo(dlcode, carId, lsh车型Model.get来源(), lsh车型Model.get品牌(),
                        lsh车型Model.get级别(), lsh车型Model.get车型(), lsh车型Model.get车型详细(), companyId, yearRate,
                        loanterm, downRate, balRate);
                if ((listInfo != null && listInfo.size() == 1) && (companyId != null && !"".equals(companyId) &&
                        yearRate != null && !"".equals(yearRate) &&
                        loanterm != null && !"".equals(loanterm) &&
                        downRate != null && !"".equals(downRate) &&
                        balRate != null && !"".equals(balRate))) {
                    quoteFinanceInfo = getQuoteFinanceInfo(quoteFinanceInfo, listInfo);
                }
            } /*else {
                if (downRate != null && !"".equals(downRate)) {
                    List listError = repository.getFinanceSettings(dlcode, carId, lsh车型Model.get来源(), lsh车型Model.get品牌(),
                            lsh车型Model.get级别(),lsh车型Model.get车型(),lsh车型Model.get车型详细(),companyId,yearRate,
                            loanterm,"",balRate,"4");
                    if (listError != null && !listError.isEmpty()) {
                        Map map = (Map) listError.get(0);
                        String downFirstRate = map.get("最低首付比例") == null ? null : map.get("最低首付比例").toString();
                        if (downFirstRate != null) {
                            quoteFinanceInfo.setMessage("最低首付比例不能低于" + downFirstRate);
                        }
                    }
                }
                if (balRate != null && !"".equals(balRate)) {
                    List listError = repository.getFinanceSettings(dlcode, carId, lsh车型Model.get来源(), lsh车型Model.get品牌(),
                            lsh车型Model.get级别(),lsh车型Model.get车型(),lsh车型Model.get车型详细(),companyId,yearRate,
                            loanterm,downRate,"","5");
                    if (listError != null && !listError.isEmpty()) {
                        Map map = (Map) listError.get(0);
                        String balFirstRate = map.get("最高尾款比例") == null ? null : map.get("最高尾款比例").toString();
                        if (balFirstRate != null) {
                            quoteFinanceInfo.setMessage("最高尾款比例不能高于" + balFirstRate);
                        }
                    }

                }
            }*/
            resultList.add(quoteFinanceInfo);
        } catch (Exception e) {
            logger.error("金融计算器程序异常", e);
        }
        return resultList;
    }

    public ResultData getMonthlyMortgagePayment(String dlcode, String carId, String companyId, String yearRate,
                                                String loanterm, String downRate, String balRate, String loanAmount, String msrp) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            //校验车型编号
            if (carId == null || "".equals(carId)) {
                resultData.setMessage("车型编号不能为空或者为null");
                return resultData;
            }
            Lsh车型Model lsh车型Model = lsh车型Repository.findOne(Integer.parseInt(carId));
            //校验根据车型编号查出的信息
            if (lsh车型Model == null) {
                resultData.setMessage("未找到相关车型信息");
                return resultData;
            }
            //校验是否有 贷款金额，
            if (loanAmount == null || "".equals(loanAmount)) {
                resultData.setMessage("请确定贷款金额");
                return resultData;
            }
            //筛选满足条件的金融方案
            List listInfo = repository.getFinanceSettingsInfo(dlcode, carId, lsh车型Model.get来源(), lsh车型Model.get品牌(),
                    lsh车型Model.get级别(), lsh车型Model.get车型(), lsh车型Model.get车型详细(), companyId, yearRate,
                    loanterm, downRate, balRate);
            // 金融方案只有一条可计算月供 或者  金融机构编号、年利率、期数、首付比例 都已确定，可计算月供
            if ((listInfo != null && listInfo.size() == 1) ||
                    (companyId != null && !"".equals(companyId) &&
                            yearRate != null && !"".equals(yearRate) &&
                            loanterm != null && !"".equals(loanterm) &&
                            downRate != null && !"".equals(downRate) &&
                            balRate != null && !"".equals(balRate))) {
                DecimalFormat df = new DecimalFormat("######0.00");
                QuoteFinanceInfo quoteFinanceInfo = new QuoteFinanceInfo();
                quoteFinanceInfo = getQuoteFinanceInfo(quoteFinanceInfo, listInfo);

                double yearRateDouble = 0.0;
                //判断 年利率 是否为 空或null，否  转换为double，是  取金融方案中的 年利率
                if (yearRate != null && !"".equals(yearRate)) {
                    yearRateDouble = Double.parseDouble(yearRate);
                } else {
                    yearRateDouble = Double.parseDouble(quoteFinanceInfo.getFinanceYearlyRate());
                }
                int loantermDouble = 0;
                //判断 期数 是否为 空或null，否  转换为int，是  取金融方案中的 期数
                if (loanterm != null && !"".equals(loanterm)) {
                    loantermDouble = Integer.parseInt(loanterm);
                } else {
                    loantermDouble = Integer.parseInt(quoteFinanceInfo.getFinanceLoanTermFin());
                }
                double loanAmountDouble = Double.parseDouble(loanAmount);

                if ("费率".equals(quoteFinanceInfo.getFinanceYearlyRateStyle())) {
                    //利率类型是 费率 的金融方案，计算月供
                    double monthlyMortgagePayment = (yearRateDouble / 100 + 1) * loanAmountDouble / loantermDouble;
                    quoteFinanceInfo.setFinanceMonthlyPayment(df.format(monthlyMortgagePayment));
                } else if ("利率".equals(quoteFinanceInfo.getFinanceYearlyRateStyle())) {
                    //利率类型是 利率 的金融方案，计算月供
                    //如果 年利率 = 0， 月供计算公式为  贷款金额 / 期数
                    if (Double.parseDouble(quoteFinanceInfo.getFinanceYearlyRate()) <= 0) {
                        double numerator = loanAmountDouble;
                        double denominator =loantermDouble;
                        quoteFinanceInfo.setFinanceMonthlyPayment(df.format(numerator / denominator));
                    } else {
                        //计算月供的分子
                        double msrpDouble = Double.parseDouble(msrp == null || "".equals(msrp) ? "0" : msrp),
                                balRateDouble = Double.parseDouble(balRate == null || "".equals(balRate) ? "0" : balRate) / 100,
                                balAccount = msrpDouble * balRateDouble;
                        double numerator = (loanAmountDouble - balAccount) * yearRateDouble / 1200 * Math.pow((1 + yearRateDouble / 1200), loantermDouble);
                        //计算月供的分母
                        double denominator = Math.pow((1 + yearRateDouble / 1200), loantermDouble) - 1;
                        //尾款利率计算
                        double balPay = balAccount * yearRateDouble / 1200;
                        quoteFinanceInfo.setFinanceMonthlyPayment(df.format(numerator / denominator + balPay));
                    }
                }
                List<QuoteFinanceInfo> list = new ArrayList<>();
                if(!Strings.isNullOrEmpty(quoteFinanceInfo.getFinanceDepositRate())) {
                    quoteFinanceInfo.setFinanceDepositPayment((new BigDecimal(quoteFinanceInfo.getFinanceDepositRate()).multiply(new BigDecimal(msrp)).divide(new BigDecimal(100))).toString());
                }
                list.add(quoteFinanceInfo);
                resultData.setResult("true");
                resultData.setPageData(new PageData(list, 0));
            }
        } catch (Exception e) {
            logger.error("金融计算器--获取月供程序异常", e);
            resultData.setMessage("金融计算器--获取月供程序异常");
        }
        return resultData;
    }

    @Override
    public ResultData getFinanceSettingsToPC(String permit, FinanceSetting financeSetting) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            if (financeSetting == null) {
                resultData.setMessage("未传入参数");
                return resultData;
            }
            String type = financeSetting.type;
            if (type == null || "".equals(type)) {
                resultData.setMessage("筛选域类型不能为空或null");
                return resultData;
            }
            String carId = financeSetting.carId;
            if (carId == null || "".equals(carId)) {
                resultData.setMessage("车型编号不能为空或null");
                return resultData;
            }

            String downRate = null;
            if (!"4".equals(type)) {
                downRate = financeSetting.downRate;
            }

            String balRate = null;
            if (!"5".equals(type)) {
                balRate = financeSetting.balRate == null || "".equals(financeSetting.balRate) ? "0" : financeSetting.balRate;
            }

            List<QuoteFinanceInfo> list = getFinanceSettings(permit, carId, financeSetting.companyId, financeSetting.yearRate,
                    financeSetting.loanTerm, downRate, balRate, "", type);
            if (list == null || list.isEmpty()) {
                resultData.setMessage("未找到相关金融方案");
                return resultData;
            }
            List resultList = new ArrayList();
            Map map = new HashMap();
            QuoteFinanceInfo quoteFinanceInfo = list.get(0);
            if ("1".equals(type)) {
                ArrayList<String> financeBankNameAry = quoteFinanceInfo.getFinanceBankNameAry();
                ArrayList<String> financeBankIDAry = quoteFinanceInfo.getFinanceBankIDAry();
                if (financeBankIDAry != null && !financeBankIDAry.isEmpty() &&
                        financeBankNameAry != null && !financeBankNameAry.isEmpty()) {
                    if (financeBankIDAry.size() == financeBankNameAry.size()) {
                        for (int i = 0; i < financeBankIDAry.size(); i++) {
                            map = new HashMap();
                            map.put("companyId", financeBankIDAry.get(i));
                            map.put("companyName", financeBankNameAry.get(i));
                            resultList.add(map);
                        }
                    } else {
                        resultData.setMessage("获取金融机构程序异常");
                        return resultData;
                    }
                } else {
                    resultData.setMessage("未找到相关金融机构 -- 金融方案");
                    return resultData;
                }
            } else if ("2".equals(type)) {
                ArrayList<String> financeLoanTerm = quoteFinanceInfo.getFinanceLoanTerm();
                if (financeLoanTerm != null && !financeLoanTerm.isEmpty()) {
                    for (int i = 0; i < financeLoanTerm.size(); i++) {
                        map = new HashMap();
                        map.put("loanTerm", financeLoanTerm.get(i));
                        resultList.add(map);
                    }
                } else {
                    resultData.setMessage("未找到相关金融期数 -- 金融方案");
                    return resultData;
                }
            } else if ("3".equals(type)) {
                ArrayList<String> financeYearlyRateAry = quoteFinanceInfo.getFinanceYearlyRateAry();
                String financeYearlyRateStyle = quoteFinanceInfo.getFinanceYearlyRateStyle();
                if (financeYearlyRateAry != null && !financeYearlyRateAry.isEmpty() && financeYearlyRateStyle != null) {
                    String[] financeYearlyRateStyleArray = financeYearlyRateStyle.split("___MARK___");
                    if (financeYearlyRateStyleArray != null && financeYearlyRateStyleArray.length == financeYearlyRateAry.size()) {
                        for (int i = 0; i < financeYearlyRateAry.size(); i++) {
                            map = new HashMap();
                            map.put("yearlyRateStyle", financeYearlyRateStyleArray[i]);
                            map.put("yearRate", financeYearlyRateAry.get(i));
                            resultList.add(map);
                        }
                    } else {
                        resultData.setMessage("获取金融利率/费率程序异常");
                        return resultData;
                    }
                } else {
                    resultData.setMessage("未找到相关金融期数 -- 金融方案");
                    return resultData;
                }
            } else if ("4".equals(type)) {
                String financeDownPaymentRate = quoteFinanceInfo.getFinanceDownPaymentRate();
                if (financeDownPaymentRate != null && !"".equals(financeDownPaymentRate)) {
                    map.put("downRate", financeDownPaymentRate);
                    resultList.add(map);
                } else {
                    resultData.setMessage("未找到相关金融首付比例 -- 金融方案");
                    return resultData;
                }
            } else if ("5".equals(type)) {
                String financeBalanceRate = quoteFinanceInfo.getFinanceBalanceRate();
                if (financeBalanceRate != null && !"".equals(financeBalanceRate)) {
                    map.put("balRate", financeBalanceRate);
                    resultList.add(map);
                } else {
                    resultData.setMessage("未找到相关金融尾款比例 -- 金融方案");
                    return resultData;
                }
            }
            resultData.setResult("true");
            resultData.setPageData(new PageData(resultList, 0));
        } catch (Exception e) {
            logger.error("pc端金融计算器程序异常", e);
            resultData.setMessage("金融计算器--pc筛选域程序异常");
        }
        return resultData;
    }

    @Override
    public ResultData getMonthlyMortgagePaymentToPC(String permit, FinanceSetting financeSetting) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            if (financeSetting == null) {
                resultData.setMessage("未传入参数");
                return resultData;
            }
            String carId = financeSetting.carId;
            if (carId == null || "".equals(carId)) {
                resultData.setMessage("车型编号不能为空或null");
                return resultData;
            }
            String carAmount = financeSetting.carAmount;
            if (carAmount == null || "".equals(carAmount)) {
                resultData.setMessage("车辆价格不能为空或者null");
                return resultData;
            }
            String balRate = financeSetting.balRate == null || "".equals(financeSetting.balRate) ? "0" : financeSetting.balRate;
            ResultData data = getMonthlyMortgagePayment(permit, carId, financeSetting.companyId, financeSetting.yearRate,
                    financeSetting.loanTerm, financeSetting.downRate, financeSetting.balRate, financeSetting.loanAmount, financeSetting.carAmount);
            if (data == null || "false".equals(data.getResult())) {
                return resultData;
            }
            PageData pageData = data.getPageData();
            List resultList = new ArrayList();
            if (pageData != null) {
                List<QuoteFinanceInfo> list = pageData.getData();
                if (list != null && !list.isEmpty()) {
                    QuoteFinanceInfo quoteFinanceInfo = list.get(0);
                    Map map = new HashMap();
                    map.put("companyId", quoteFinanceInfo.getFinanceBankID());              //金融机构编号
                    map.put("companyName", quoteFinanceInfo.getFinanceBankName());          //金融机构名称
                    map.put("yearRate", quoteFinanceInfo.getFinanceYearlyRate());           //年利率
                    map.put("yearRateStyle", quoteFinanceInfo.getFinanceYearlyRateStyle()); //利率/费率
                    map.put("loanTerm", quoteFinanceInfo.getFinanceLoanTermFin());          //期数
                    map.put("downRate", quoteFinanceInfo.getFinanceDownPaymentRate());      //首付比率
                    map.put("balRate", quoteFinanceInfo.getFinanceBalanceRate());           //尾款比率
                    map.put("loanAmount", quoteFinanceInfo.getFinanceLoanPayment());        //贷款金额
                    map.put("loanStyle", quoteFinanceInfo.getFinanceLoanStyle());           //贷款类型
                    map.put("depositRate", quoteFinanceInfo.getFinanceDepositRate());       //保证金比率
                    String depositPriceStr = quoteFinanceInfo.getFinanceDepositRate();
                    if (depositPriceStr != null && !"".equals(depositPriceStr)) {
                        double depositPrice = Double.parseDouble(depositPriceStr) * Double.parseDouble(carAmount) / 100;
                        map.put("depositPrice", depositPrice);   //保证金金额
                    } else {
                        map.put("depositPrice", 0);   //保证金金额
                    }
                    map.put("hotLevel", quoteFinanceInfo.getFinanceHotLevel());             //热销级别
                    map.put("mortgageStyle", quoteFinanceInfo.getFinanceMortgageStyle());   //按揭类型
                    map.put("productStyle", quoteFinanceInfo.getFinanceProductStyle());     //产品类型
                    map.put("monthlyPayment", quoteFinanceInfo.getFinanceMonthlyPayment()); //月供
                    map.put("productId", quoteFinanceInfo.getFinanceProductNum()); //金融产品编码
                    map.put("financeId", quoteFinanceInfo.getFinanceProjectID()); //金融方案ID

                    if (financeSetting.carId != null && !"".equals(financeSetting.carId)) {
                        getFinanceFee(quoteFinanceInfo.getFinanceBankName(), quoteFinanceInfo.getFinanceBankID(),
                                quoteFinanceInfo.getFinanceProductStyle(), financeSetting.carId, financeSetting.loanAmount, map);
                    }
                    resultList.add(map);
                }
            }
            resultData.setResult("true");
            resultData.setPageData(new PageData(resultList, 0));
        } catch (Exception e) {
            logger.error("pc端金融计算器程序异常", e);
            resultData.setMessage("金融计算器--pc筛选域程序异常");
        }
        return resultData;
    }

    private QuoteFinanceInfo getQuoteFinanceInfo(QuoteFinanceInfo quoteFinanceInfo, List list) {
        Map map = (Map) list.get(0);
        quoteFinanceInfo.setFinanceBankName(map.get("金融机构") == null ? null : map.get("金融机构").toString());
        quoteFinanceInfo.setFinanceBankID(map.get("金融机构编号") == null ? null : map.get("金融机构编号").toString());
        quoteFinanceInfo.setFinanceID(map.get("金融编号") == null ? null : map.get("金融编号").toString());
        quoteFinanceInfo.setFinanceProjectID(map.get("金融编号") == null ? null : map.get("金融编号").toString());
        quoteFinanceInfo.setFinanceYearlyRate(map.get("年利率") == null ? null : map.get("年利率").toString());
        quoteFinanceInfo.setFinanceYearlyRateStyle(map.get("利率状态") == null ? null : map.get("利率状态").toString());
        quoteFinanceInfo.setFinanceDepositRate(map.get("保证金比例") == null ? null : map.get("保证金比例").toString());
        quoteFinanceInfo.setFinanceDownPaymentRate(map.get("最低首付比例") == null ? null : map.get("最低首付比例").toString());
        quoteFinanceInfo.setFinanceIsBalancePay(map.get("是否尾款") == null ? null : map.get("是否尾款").toString());
        quoteFinanceInfo.setFinanceBalanceRate(map.get("最高尾款比例") == null ? null : map.get("最高尾款比例").toString());
        quoteFinanceInfo.setFinanceLoanTermFin(map.get("期数") == null ? null : map.get("期数").toString());
        quoteFinanceInfo.setFinanceLoanTermIsFixed(map.get("是否固定") == null ? null : map.get("是否固定").toString());
        quoteFinanceInfo.setFinanceHotLevel(map.get("热销级别") == null ? null : map.get("热销级别").toString());
        quoteFinanceInfo.setFinanceWorkStyle(map.get("业务类型") == null ? null : map.get("业务类型").toString());
        quoteFinanceInfo.setFinanceMortgageStyle(map.get("按揭类型") == null ? null : map.get("按揭类型").toString());
        quoteFinanceInfo.setFinanceProductStyle(map.get("产品分类") == null ? null : map.get("产品分类").toString());
        quoteFinanceInfo.setFinanceLoanStyle(map.get("贷款类型") == null ? null : map.get("贷款类型").toString());
        quoteFinanceInfo.setFinanceProductNum(map.get("产品编码") == null ? null : map.get("产品编码").toString());
        return quoteFinanceInfo;
    }


    private Map getFinanceFee(String bankName, String bankId, String productStyle, String carId, String loanAmount, Map map) {
        Lsh车型Model lsh车型Model = lsh车型Repository.findby车型编号(Integer.parseInt(carId));
        if (lsh车型Model != null) {
            String financeFeeType = null;
            //需求1257 大昌行金融没有贴息和非贴息
            /*if (bankName != null &&
                    (bankName.equals("奔驰金融")
                            || bankName.equals("奔驰租赁"))) {
                if ("smart".equals(lsh车型Model.get品牌())) {
                    financeFeeType = "smart";
                } else if (!StringUtils.isNullOrBlank(productStyle) &&
                        "贴息产品".equals(productStyle)) {
                    financeFeeType = "MBPC（CPN）";
                } else {
                    financeFeeType = "MBPC（Non CPN）";
                }
            }*/
            List listFinanceFee = repository.getFinanceFee(bankId, financeFeeType);
            if (listFinanceFee != null && !listFinanceFee.isEmpty()) {
                Map mapFinanceFee = (Map) listFinanceFee.get(0);
                String isFix = mapFinanceFee.get("是否固定") == null ? null : mapFinanceFee.get("是否固定").toString();
                String fixFee = mapFinanceFee.get("固定手续费") == null ? null : mapFinanceFee.get("固定手续费").toString();
                String noFixFee = mapFinanceFee.get("固定费率") == null ? null : mapFinanceFee.get("固定费率").toString();
                if ("是".equals(isFix)) {
                    map.put("financeFee", fixFee);
                } else {
                    if (noFixFee != null && !"".equals(noFixFee)) {
                        double financeFeeRate = Double.parseDouble(noFixFee);
                        double financeFee = Double.parseDouble(loanAmount) * financeFeeRate / 100;
                        DecimalFormat df = new DecimalFormat("######0.00");
                        map.put("financeFee", df.format(financeFee));
                    }
                }
            }
        }
        return  map;
    }



    public ResultData getLastReplace(String permit) {
        ResultData resultData = new ResultData("false", null, null);
        try {
            List list = repository.getLastReplace(permit);
            resultData.setResult("true");
            resultData.setPageData(new PageData(list, 1));
        } catch (Exception e) {
            logger.error("查询金融手续费最新更新时间和账户异常", e);
        }
        return resultData;
    }

    /**
     * liuweilong 2017-5-8  --------------------获取基础设置---
     * @param permit
     * @param name
     * @return
     */
    public ResultData getSettings(String permit,String name){
        ResultData resultData = new ResultData("false", null, null);
        try {
            Itask基础设置Model model=itask基础设置Repository.finByPermitAndName(permit,name);
            Map  result = new HashMap();
            if(model!=null) {

                result.put("type",model.get值());
                List a=new ArrayList();
                a.add(result);
                resultData.setResult("true");
                resultData.setMessage("查询金融服务费类型成功");
                resultData.setPageData(new PageData(a, 1));
            }
            else{
                result.put("type",0);
                List a=new ArrayList();
                a.add(result);
                resultData.setResult("true");
                resultData.setMessage("查询金融服务费类型成功");
                resultData.setPageData(new PageData(a, 1));
            }
        } catch (Exception e) {
            logger.error("查询金融服务费类型失败", e);
        }
        return resultData;
    }

    /**
     * create liuweilong 2017-5-8  --------------------保存基础设置---  02:金融服务费  01：其他服务费
     * @param permit
     * @param name
     * @return
     */


    public ResultData saveSettings(String permit,String name,String type,String userName){
        ResultData resultData = new ResultData();
        try {

            Itask基础设置Model model=itask基础设置Repository.finByPermitAndName(permit,name);
            Map  result = new HashMap();
            if(model!=null) {
                model.set值(type);
            }
            else{
                model=new Itask基础设置Model();
                model.set许可(permit);
                model.set值(type);
                model.set更新时间(new Timestamp(new Date().getTime()));
                model.set更新账号(userName);
                model.set设置项目("金融服务费");
            }
            //保存提交数据
            itask基础设置Repository.save(model);
            resultData.setResult("true");
            resultData.setMessage("修改成功");
        } catch (Exception e) {
            resultData.setMessage("修改失败");
            resultData.setResult("false");
            logger.error("查询金融手续费最新更新时间和账户异常", e);
        }
        return resultData;

    }

    @Override
    public void exportFinanceAccountInfo(String permit, HttpServletResponse response, FinanceService.GetExportFinanceAccountInfoParam getExportFinanceAccountInfoParam) {
        try{
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/LSH_经销商_金融贷款客户管理台账导出模板.xlsx")
                    .setFileName("经销商_金融贷款客户管理台账导出模板.xlsx")
                    .setSource(ExportFinanceAccountInfoSource)
                    .setStaticSheet(false)
                    .setAutoRowExtended(true)
                    .addParam("permit", permit)
                    .addParam("cusName", getExportFinanceAccountInfoParam.cusName)
                    .addParam("cusTel", getExportFinanceAccountInfoParam.cusTel)
                    .addParam("cusType", getExportFinanceAccountInfoParam.cusType)
                    .addParam("companyName", getExportFinanceAccountInfoParam.companyName)
                    .addParam("state", getExportFinanceAccountInfoParam.state)
                    .addParam("pageSize", getExportFinanceAccountInfoParam.getPageSize())
                    .addParam("pageIndex", getExportFinanceAccountInfoParam.getPageIndex())
                    .addParam("applyStartDate", getExportFinanceAccountInfoParam.applyStartDate)
                    .addParam("applyEndDate", getExportFinanceAccountInfoParam.applyEndDate)
                    .addParam("applyPassStartDate", getExportFinanceAccountInfoParam.applyPassStartDate)
                    .addParam("applyPassEndDate", getExportFinanceAccountInfoParam.applyPassEndDate)
                    .addParam("loanStartDate", getExportFinanceAccountInfoParam.loanStartDate)
                    .addParam("loanEndDate", getExportFinanceAccountInfoParam.loanEndDate);
            reportService.export(context,response);
        } catch (Exception e) {
            logger.error("导出金融贷款客户管理台账异常", e);
        }
    }


    @Override
    public void exportFinanceLoanInfo(String permit, HttpServletResponse response, GetExportFinanceAccountInfoParam getExportFinanceAccountInfoParam) {
        try{
            ExcelReportContext context = new ExcelReportContext();
            context.setTemplate("templates/LSH_经销商_金融贷款客户管理导出模板.xlsx")
                    .setFileName("经销商_金融贷款客户管理导出模板.xlsx")
                    .setSource(ExportFinanceLoanInfoSource)
                    .setStaticSheet(false)
                    .setAutoRowExtended(true)
                    .addParam("permit", permit)
                    .addParam("cusName", getExportFinanceAccountInfoParam.cusName)
                    .addParam("cusTel", getExportFinanceAccountInfoParam.cusTel)
                    .addParam("cusType", getExportFinanceAccountInfoParam.cusType)
                    .addParam("companyName", getExportFinanceAccountInfoParam.companyName)
                    .addParam("state", getExportFinanceAccountInfoParam.state)
                    .addParam("pageSize", getExportFinanceAccountInfoParam.getPageSize())
                    .addParam("pageIndex", getExportFinanceAccountInfoParam.getPageIndex())
                    .addParam("applyStartDate", getExportFinanceAccountInfoParam.applyStartDate)
                    .addParam("applyEndDate", getExportFinanceAccountInfoParam.applyEndDate)
                    .addParam("applyPassStartDate", getExportFinanceAccountInfoParam.applyPassStartDate)
                    .addParam("applyPassEndDate", getExportFinanceAccountInfoParam.applyPassEndDate)
                    .addParam("loanStartDate", getExportFinanceAccountInfoParam.loanStartDate)
                    .addParam("loanEndDate", getExportFinanceAccountInfoParam.loanEndDate);

            reportService.export(context,response);
        } catch (Exception e) {
            logger.error("导出金融贷款客户管理异常", e);
        }
    }

    @Override
    public ResultData saveDealerCustomFinanceProductHotRank(String permit, SaveDealerCustomFinanceProductHotRankReq req) {
        logger.info("saveDealerCustomFinanceProductHotRank传入参数为:permit" + permit + JsonObjectUtils.writeAsJson(req));
        String errMsg = "保存金融产品热销级别异常";
        try {
            // 1.数据校验
            if (req.fiId == null || req.rank == null) {
                return new ResultData("false", "传入参数为空", null);
            }
            // 2.保存或修改数据
            // 在finance_product_hot_rank中查找以前经销商有没有自定义相关的金融编号
            FinanceProductHotRankModel mo = fiProHoRaRep.getMoByFiIdAndPermit(req.fiId, permit);
            if (mo == null) { // 以前没有自定义集团金融产品的热销级别
                FinanceProductHotRankModel fiProHoRaMo = new FinanceProductHotRankModel();
                fiProHoRaMo.setFiId(req.fiId);
                fiProHoRaMo.setPermit(permit);
                fiProHoRaMo.setHotRank(req.rank + "");
                fiProHoRaRep.save(fiProHoRaMo);
            } else { // 以前有自定义
                mo.setHotRank(req.rank + "");
                fiProHoRaRep.save(mo);
            }
            return new ResultData("true", null, null);
        } catch (Exception e) {
            logger.warn(errMsg, e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultData("false", errMsg, null);
        }
    }

    @Override
    public ResultData getFinanceProduceNum(String permit, String companyName, String carCode) {
        ResultData resultData = new ResultData("false", null, null);
        List list = new ArrayList();
        List values = new ArrayList();
        StringBuffer sb = new StringBuffer();
        Lsh车型Model lsh车型Model = null;
        Lsh金融机构设置Model lsh金融机构设置Model1 = null, lsh金融机构设置Model2 = null;
        String id1 = null, id2 = null;

        if (!Strings.isNullOrEmpty(carCode)) {
            lsh车型Model = lsh车型Repository.findby车型编号(Integer.parseInt(carCode));
        } else {
            logger.error("获取金融产品编码--参数 carCode(车型编号) 为空");
            resultData.setMessage("查询金融产品编码失败");
            return resultData;
        }
        if (!StringUtils.isNullOrBlank(companyName)) {
            lsh金融机构设置Model1 = lsh金融机构设置Repository.getModelByPermitAndCompanyName(permit, companyName);
            lsh金融机构设置Model2 = lsh金融机构设置Repository.getModelByPermitAndCompanyName("LSH", companyName);
            if (lsh金融机构设置Model1 != null) {
                id1 = lsh金融机构设置Model1.get金融机构编号() + "";
            }
            if (lsh金融机构设置Model2 != null) {
                id2 = lsh金融机构设置Model2.get金融机构编号() + "";
            }
        } else {
            resultData.setResult("true");
            return resultData;
        }
        if (lsh车型Model != null) {
            list = repository.getFinanceProduceNum(permit, id1, id2, carCode, lsh车型Model.get来源(), lsh车型Model.get品牌(), lsh车型Model.get级别(), lsh车型Model.get车型(), lsh车型Model.get车型详细());
            if (list != null && !list.isEmpty()) {
                for (Object o : list) {
                    Map map = (Map) o;
                    if (sb == null || "".equals(sb.toString())) {
                        sb.append(map.get("产品编码") == null ? null : map.get("产品编码").toString());
                    } else {
                        sb.append(",");
                        sb.append(map.get("产品编码") == null ? null : map.get("产品编码").toString());
                    }
                }
                values.add(sb.toString());
            }
        }
        resultData.setResult("true");
        resultData.setMessage(sb.toString());
        resultData.setPageData(new PageData(values, 1));
        return resultData;
    }

    public ResultData getFinanceFee (String carId, String loanAmount) {
        ResultData resultData = new ResultData("false", null, null);
        Map map = new HashMap();
        map = getFinanceFee("奔驰租赁","2", "", carId, loanAmount, map);
        List list = new ArrayList();
        list.add(map);
        resultData.setResult("true");
        resultData.setPageData(new PageData(list, 1));
        return resultData;
    }

    @Override
    public ResultData getSuitableArea() {
        ResultData resultData = new ResultData("false",null,null);
        PageData pageData = null;
        try{
            pageData = repository.getSuitableArea();
            resultData.setResult("true");
            resultData.setPageData(pageData);
            resultData.setMessage(pageData.getTotal()+"");
        }catch(Exception e){
            resultData.setMessage("程序异常");
            logger.error("查询适用单店列表异常", e);
        }
        return resultData;
    }

    @Override
    public ResultData getSuitableStore(Integer id) {
        ResultData resultData = new ResultData("false",null,null);
        PageData pageData = null;
        try{
            pageData = repository.getSuitableStore(id);
            resultData.setResult("true");
            resultData.setPageData(pageData);
            resultData.setMessage(pageData.getTotal()+"");
        }catch(Exception e){
            resultData.setMessage("程序异常");
            logger.error("查询适用区域列表异常", e);
        }
        return resultData;
    }
    @Override
    public List getFinDefeatedReson(){
        return repository.getFinDefeatedReson();
    }

    @Override
    public ResultData getFinanceInfoByName(String name){
        ResultData resultData = new ResultData("false",null,null);
        PageData pageData = null;
        try{
            pageData = repository.getFinanceInfoByName(name);
            resultData.setResult("true");
            resultData.setPageData(pageData);
            resultData.setMessage(pageData.getTotal()+"");
        }catch(Exception e){
            resultData.setMessage("程序异常");
            logger.error("查询金融机构异常", e);
        }
        return resultData;
    }

}
